#!/home/oracle/environments/my_env/bin/python
import boto3,pprint,argparse,sys,time,json

pp = pprint.PrettyPrinter(indent=2)
client = boto3.client('rds')
t=0
maxt=1600
sleepint=60

if len(sys.argv)== 1:
  print ("\n")
  print (" **** Use " + sys.argv[0] + " -h for filter options")
  print ("\n")
  sys.exit(1)

parser = argparse.ArgumentParser()
parser.add_argument('-i','--instname',help='Instance Name to rename to', required=True, default='')
#parser.add_argument('-r','--newinstname',help='New Instance name ', required=True ,default='')
parser.add_argument('-a','--apply',help='Apply immediately <True|False>', required=True)
#J
args=parser.parse_args()

## Check if Instance exists..
with open ('instances.json') as f:
  data = json.load(f)

try:
 for instance in data['instances']:

  response = client.modify_db_instance(
    DBInstanceIdentifier    = instance[args.instname]['DBInstanceIdentifier'],
    NewDBInstanceIdentifier = instance[args.instname]['NewDBInstanceIdentifier'],
#    DBSubnetGroupName       = instance[args.instname]['DBSubnetGroupName'],
    MultiAZ                 = instance[args.instname]['MultiAZ'],
    PubliclyAccessible      = instance[args.instname]['PubliclyAccessible'],
    AutoMinorVersionUpgrade = instance[args.instname]['AutoMinorVersionUpgrade'],
    OptionGroupName         = instance[args.instname]['OptionGroupName'],
    StorageType             = instance[args.instname]['StorageType'],
    Iops                    = instance[args.instname]['Iops'],
    AllocatedStorage        = instance[args.instname]['AllocatedStorage'],
    DBParameterGroupName    = instance[args.instname]['DBParameterGroupName'],
    DeletionProtection      = instance[args.instname]['DeletionProtection'],
    DBInstanceClass         = instance[args.instname]['DBInstanceClass'],
    VpcSecurityGroupIds     = instance[args.instname]['VpcSecurityGroupIds'],
    ApplyImmediately        = bool(args.apply)

    )
  pp.pprint(response)

except Exception as error:
  print(error)
  sys.exit(1)

print('sleeping.. ' + str(sleepint) + ' seconds')
time.sleep(sleepint)

while t < maxt:
   response = client.describe_db_instances(DBInstanceIdentifier = instance[args.instname]['NewDBInstanceIdentifier'])
   for inst in response['DBInstances']:
     if inst['DBInstanceIdentifier'] == instance[args.instname]['NewDBInstanceIdentifier'] and inst['DBInstanceStatus'] == 'available':
        print('Instance modification completed :' + inst['DBInstanceIdentifier'] + ' Status : '+  inst['DBInstanceStatus'])
        sys.exit(1)
     else:
       if inst['DBInstanceIdentifier'] == instance[args.instname]['DBInstanceIdentifier'] or  NewDBInstanceIdentifier == instance[args.instname]['NewDBInstanceIdentifier']:
        print('Instance ' + inst['DBInstanceIdentifier'] + ' Status : '+  inst['DBInstanceStatus'])
        print('Renaming may be in progress. Be patient or ctrl-c' )
        print (str(t) + ':' + str(maxt) + ' seconds')
        time.sleep(sleepint)
        t = t + sleepint
print('Loop max reached. Exiting..')

