#!/usr/bin/env python3
# code=UTF-8
# Copyright 2013-2014 James P Goodwin bkp@jlgoodwin.com
# This is the restore program that goes with bkp created by James
import sys
import os
import re
from optparse import OptionParser
from bkp_core import bkp_conf
from bkp_core.rstr_mod import RestoreJob
import traceback
import platform

def main(options, args):
    """ The main driver for the bkp utility """
    os.set_blocking(sys.stderr.fileno(),1)

    config = bkp_conf.config(options.config_file)

    restore_job = RestoreJob(config)

    if options.dryrun:
        restore_job.set_dryrun(True)

    if options.verbose:
        restore_job.set_verbose(True)

    return restore_job.restore(options.machine,options.restore_path,options.exclude,options.asof,args)


if __name__ == '__main__':
    parser = OptionParser(usage="usage: %prog [options] restore_pattern { list of restore patterns }", description="A restore script for restoring files backed up to {s3,file, or sftp} using bkp. A restore pattern is a python regular expression matching a path to restore ex: /home/james/My.*/.*\.jpg$")
    parser.add_option("-a","--asof", dest="asof", default="", help="date time to restore back to in YYYY.MM.DD.HH.MM.SS format. Default is now.")
    parser.add_option("-v","--verbose", dest="verbose", action="store_true", default=False, help="Log all activity to console")
    parser.add_option("-d","--dryrun", dest="dryrun", action="store_true", default=False, help="Do everything except actually perform actions")
    parser.add_option("-f","--file", dest="config_file",default="~/.bkp/bkp_config", help="Load config from this file default is ~/.bkp/bkp_config")
    parser.add_option("-m","--machine", dest="machine",default=platform.node(), help="Machine name to restore for. Default is this machine.")
    parser.add_option("-p","--path", dest="restore_path",default="/", help="Alternate existing target directory use as root for restore. Default is the root directory of backed up file.")
    parser.add_option("-e","--exclude",dest="exclude",action="append", default=[],help="Pattern on ENTIRE target path to exclude files from restore. Use multiple args to add multiple filters." )

    (options,args) = parser.parse_args()

    try:
        ret = main(options,args)
    except:
        tb = traceback.format_exc()
        print(tb, file=sys.stderr)
        exit(1)

    exit(ret)
