import os, sys, subprocess, boto3
def assume_role(sessionname):
  sts_client = boto3.client('sts', region_name = 'us-west-2')
  # Call the assume_role method of the STSConnection object and pass the role
  # ARN and a role session name.
  assumedRoleObject = sts_client.assume_role(
      RoleArn="arn:aws:iam::673385534282:role/Clio_PHC_Analytics",
      RoleSessionName=sessionname
  )

  # From the response that contains the assumed role, get the temporary 
  # credentials that can be used to make subsequent API calls
  credentials = assumedRoleObject['Credentials']
  return credentials

def s3_assume_role_client(credentials):
  # Use the temporary credentials that AssumeRole returns to make a 
  # connection to Amazon S3  
  s3_client = boto3.client(
      's3',
      aws_access_key_id = credentials['AccessKeyId'],
      aws_secret_access_key = credentials['SecretAccessKey'],
      aws_session_token = credentials['SessionToken'],
      region_name = 'us-west-2'
  )
  return s3_client
def sqs_assume_role_client(credentials):
  # Use the temporary credentials that AssumeRole returns to make a 
  # connection to Amazon S3  
  sqs_client = boto3.client(
      'sqs',
      aws_access_key_id = credentials['AccessKeyId'],
      aws_secret_access_key = credentials['SecretAccessKey'],
      aws_session_token = credentials['SessionToken'],
      region_name = 'us-west-2'
  )
  return sqs_client

def db_type():
    if subprocess.check_output(['/usr/bin/psql', '--tuples-only', '--command', 'select pg_is_in_recovery()']).strip() == 'f':
      db_type = 'master'
    else:
      db_type = 'replica'
    return db_type

def write_pidfile_or_die(pidfile):
  pid = str(os.getpid())
  if os.path.isfile(pidfile):
    print "%s already exists, exiting" % pidfile
    sys.exit()
  else:
    file(pidfile, 'w').write(pid)

def remove_pidfile(pidfile):
  if os.path.isfile(pidfile):
    print "removing pidfile"
    os.unlink(pidfile)
