#!/usr/bin/env python

from __future__ import print_function
import os
import argparse
import warnings

import dotenv


parser = argparse.ArgumentParser()
parser.add_argument("file_path", help="the absolute path of the .env file you want to use")
parser.add_argument("action", help="what you want to do with the .env file (get, set, unset)", nargs='?')
parser.add_argument("key", help="the environment key you want to set", nargs='?')
parser.add_argument("value", help="the value you want to set 'key' to", nargs='?')
parser.add_argument("--force", action="store_true", help="force writing even if the file at the given path doesn't end in .env")
args = parser.parse_args()

if not os.path.exists(args.file_path):
    if args.force:
        open(args.file_path, 'a').close()
    else:
        warnings.warn("there doesn't appear to be a file at {}, use --force to proceed".format(args.file_path))
        exit(1)

if not args.force:
    if not args.file_path.endswith(".env"):
        warnings.warn("the file {} doesn't appear to be a .env file, use --force to proceed".format(args.file_path))
        exit(1)

if args.action == None:
    with open(args.file_path) as f:
        print(f.read())

elif args.action == "get":
    stored_value = dotenv.get_key(args.file_path, args.key)
    if stored_value != None:
        print(args.key)
        print(stored_value)
    else:
        exit(1)

elif args.action == "set":
    success, key, value = dotenv.set_key(args.file_path, args.key, args.value)
    if success != None:
        print("{}: {}".format(key, value))
    else:
        exit(1)

elif args.action == "unset":
    success, key = dotenv.unset_key(args.file_path, args.key)
    if success != None:
        print("unset {}".format(key))
    else:
        exit(1)

# Need to investigate if this can actually work or if the scope of the new environ variables
# Expires when python exits
#
# elif args.action == "load":
#     success = dotenv.load_dotenv(args.file_path)
#     if success != None:
#         print("loaded %s into environment" % args.file_path)
#     else:
#         exit(1)
