#!/usr/bin/env python

from __future__ import print_function

import os
import shutil
import sys
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-T", "--tablespace-mapping",
                  dest="tablespace_mapping",
                  default=[],
                  action="append",
                  help="Relocate the tablespace in directory olddir to newdir",
                  metavar="olddir=newdir")
(options, args) = parser.parse_args()

tablespace_mapping = {}
for mapping in options.tablespace_mapping:
    try:
        olddir, newdir = mapping.split('=')
    except:
        print("error: invalid tablespace mapping (%s)" % mapping, file=sys.stderr)
        sys.exit(1)
    tablespace_mapping[olddir]=newdir

if len(args) != 3:
    print("usage: %s base incremental destination" % sys.argv[0], file=sys.stderr)
    sys.exit(1)

base=args[0]
incr=args[1]
dest=args[2]

if os.path.exists(dest):
    print("error: destination must not exist (%s)" % dest, file=sys.stderr)
    sys.exit(1)

profile=open(os.path.join(incr, 'backup_profile'), 'r')

for line in profile:
    if line.strip() == 'FILE LIST':
        break

shutil.copytree(incr, dest, symlinks=True)

# tablespaces preparation
incr_tblspc = os.path.join(incr, 'pg_tblspc')
dest_tblspc = os.path.join(dest, 'pg_tblspc')
for tblspc in os.listdir(incr_tblspc):
    incr_file = os.path.join(incr_tblspc, tblspc)
    dest_file = os.path.join(dest_tblspc, tblspc)
    if not os.path.islink(incr_file):
        print("error: illegal file in source pg_tblspc directory (%s)" % incr_file, file=sys.stderr)
        sys.exit(1)
    old_target = os.readlink(incr_file)
    if old_target not in tablespace_mapping:
        print("error: missing tablespace mapping (%s)" % old_target, file=sys.stderr)
        sys.exit(1)
    new_target = tablespace_mapping[old_target]
    os.unlink(dest_file)
    os.symlink(new_target, dest_file)
    shutil.copytree(old_target, new_target)

for line in profile:
    tblspc, lsn, sent, date, size, path = line.strip().split('\t')
    if lsn == '\\N':
        continue
    if tblspc != '\\N':
        path = os.path.join('pg_tblspc', tblspc, path)
    base_file = os.path.join(base, path)
    dest_file = os.path.join(dest, path)
    shutil.copy2(base_file, dest_file)
