#!/usr/bin/env python

import argparse
import os
import subprocess
import string
import sys
import shutil
from ansible_vault import Vault

def create_credentials():
    print("Creating Terraform Credentials")
    creds_file = os.path.expanduser("~/.aws/credentials")
    backup_file = os.path.expanduser("~/.aws/credentials.terrarist.bak")
    
    if os.path.exists(backup_file):
        os.remove(backup_file)
    if os.path.exists(creds_file):
        shutil.copy(creds_file, backup_file)
        
    f = open(creds_file, "w+")
    f.write("[default]\n")
    writer = "aws_access_key_id=" + data["aws_access_key"] + "\n"
    f.write(writer)
    writer = "aws_secret_access_key=" + data["aws_secret_key"] + "\n"
    f.write(writer)

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        description='Securely wrap terraform like a terrarist!')
    parser.add_argument('action', choices=[
                        'plan', 'apply', 'import', 'init', 'destroy'], help='Terraform action to execute')
    parser.add_argument('--vault', '--ansible-vault', dest='vault_file',
                        default='terraform.vault', required=False, help='Ansible Vault File')
    parser.add_argument('--vault-password-file', dest='vault_password',
                        required=True, help='Ansible Vault Password File')
    parser.add_argument('--environment', dest='environment', default='dev',
                        required=False, help='Production, Staging, etc...')
    parser.add_argument('--no-landscape', action="store_true", dest="pretty_output",
                        required=False, help='Only define this if you do not want pretty output.')

    args, options = parser.parse_known_args()

    if not os.path.isfile(args.vault_file):
        sys.stderr.write("Ansible vault file does not exist.\n")
        sys.exit(3)

    if not os.path.isfile(args.vault_password):
        sys.stderr.write("Ansible vault password does not exist.\n")
        sys.exit(3)

    password = open(args.vault_password).read().strip()

    vault = Vault(password)
    data = vault.load(open(args.vault_file).read())

    create_credentials()

    cmd = ["terraform", args.action, "--var",
           "environment=%s" % args.environment]

    for key, value in data.items():
        cmd.append("--var")
        cmd.append("'%s=%s'" % (key, value))

    for option in options:
        cmd.append(option)

    if args.action == 'plan':
        try:
            landscape = shutil.which('landscape')  # Pretty terraform output
            if landscape is not None and not args.pretty_output:
                cmd.append(" | landscape")
        except:
            landscape = os.system('which landscape')
            if landscape != 256 and not args.pretty_output:
                cmd.append(" | landscape")

    if sys.version_info[0] < 3:  # Python 2
        x = os.system(string.join(cmd))
        sys.exit(x)
    else:  # Python 3
        x = os.system(' '.join(cmd))
        sys.exit(x)