from datetime import datetime
import boto3
import argparse
from dateutil.tz import tzutc

parser = argparse.ArgumentParser(description="clones rds instances from id to specific point in time")

parser.add_argument('-p', '--profile', required=True, dest='profile', action='store',
                    help='aws account to use')

parser.add_argument('-s', '--source', required=True, dest='source', action='store',
                    help='source db to clone')

parser.add_argument('-n', '--name', required=True, dest='name', action='store',
                    help='new database identifier')

parser.add_argument('-r', '--region', required=False, dest='region',
                    action='store',
                    help='string to search in Name Tag',
                    default='us-west-2')

parser.add_argument('-t', '--time', required=False, dest='date', action='store',
                    default="2017-02-11T00:43:00",
                    help='format of date string %Y-%m-%dT%H:%M:%S in UTC"')

args = parser.parse_args()

point_in_time = datetime.strptime(args.date, "%Y-%m-%dT%H:%M:%S").replace(tzinfo=tzutc())

sesh = boto3.Session(profile_name=args.profile, region_name=args.region)

rds = sesh.client('rds')

source = rds.describe_db_instances(DBInstanceIdentifier=args.source)['DBInstances'][0]
subnet = source['DBSubnetGroup']['DBSubnetGroupName']

recovery_resp = rds.restore_db_instance_to_point_in_time(
    SourceDBInstanceIdentifier=args.source,
    TargetDBInstanceIdentifier=args.name,
    RestoreTime=point_in_time,
    DBSubnetGroupName=subnet,
    Tags=[{'Key': 'project', 'Value': 'user-restoration'}])

print(recovery_resp)
