#!/usr/bin/env python

import sys, os, subprocess

# NOTES / TODO

# [_] pop(0)s context hints until it doesn't find anymore so you can write
#     them in any order:
#       - um py if
#       - um if ruby
#       - um js array reverse
#       - um reverse python array
#
# [_] remembers prior language context, so if you do `um bash if file exists`
#     then next time you can just say `um if string equals` and it does bash
#
# [_] data-driven lookup to allow for always-excellent bash completion
#
# [_] make this into first project for new students??
#
# [_] make OS-aware
#
# [_] prints context and summaries with syntax hilighting

# USAGE: just make shit up i guess

def um(args):
    if len(args) == 0:
        print("ok")
        sys.exit(0)

    post_processor = lambda cmd: None

    if args[0] == "ok":
        args.pop(0)
        cmd = do(args)
        post_processor = lambda cmd: subprocess.call(cmd.split(' '))
    elif args[0].startswith("alias") or args[0].startswith("function"):
        do_alias(args.pop(0), args.pop(0), args)
    elif args[1].startswith("alias") or args[1].startswith("function"):
        do_alias(args.pop(1), args.pop(0), args)
    else:
        cmd = do(args)

    print(cmd)
    post_processor(cmd)

def read_file(filename):
    fh = open(filename, 'r')
    return fh.read().strip()

def dotfile_dir():
    home = os.environ["HOME"]
    dir_name = read_file("{0}/.dotfile_directory".format(home))
    return "{0}/{1}".format(home, dir_name)

def append_line(filename, string):
    fh = open(filename, 'a')
    fh.write(string)
    return True

def show_end_context(filename):
    fh = open(filename, 'r')
    lines = fh.readlines()
    print("".join(lines[-5:]))

def do_alias(which, subcmd, args):
    which = {
        "alias": "alias",
        "aliases": "alias",
        "function": "function",
        "functions": "function"
    }[which]

    file_name = {
        "alias": "bash_aliases",
        "function": "bash_functions"
    }[which]

    path = "{0}/sh/{1}".format(dotfile_dir(), file_name)

    if subcmd == "add":
        pattern = {
            "alias":    "alias {0}='{1}'",
            "function": "function {0} {{ {1}; }}"
        }[which]

        string = pattern.format(args[0], " ".join(args[1:]))
        string_c = color(string, "green")
        path_c = color(path, "red")

        confirmation = input("Append {0} to {1}?: ".format(string_c, path_c))
        if confirmation == "" or confirmation == "y":
            append_line(path, string)
            show_end_context(path)

        sys.exit(0)

def do(args):
    if args[0] == "if":
        if args[1] == "file":
            if args[2] == "exists":
                return '[ -e "$file" ]'

        elif args[1] == "string":
            if args[2] == "equals":
                return '[ "$string" = "$file" ]'

    elif args[0] == "android":
        if args[1] == "activate":
            if args[2] == "developer":
                return 'Settings -> About -> Tap "Build number" seven times'

    elif args[0] == "bash":
        if args[1] == "delete":
            if args[2] == "function":
                return 'unset -f $funcName'

    elif args[0] == "string":
        return '${String%ABC}'

    elif args[0] == "ok":

        if args[1] == 'start_postgres':
            # OS X only
            return 'pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start'

        elif args[1] == 'stop_postgres':
            # OS X only
            return 'pg_ctl -D /usr/local/var/postgres stop -s -m fast'

        elif args[1] == 'check_postgres':
            return 'pg_ctl -D /usr/local/var/postgres status'

        else:
            return None

        if cmd:
            print(cmd)

def color(string, name, bold=False):
    attr = []

    num = {
        "green": 32,
        "red": 31,
    }[name]

    attr.append(num)

    if bold:
        attr.append(1)

    attrs = ";".join(map(lambda a: str(a), attr))

    return '\x1b[{0}m{1}\x1b[0m'.format(attrs, string)

um(sys.argv[1:])
