#!/usr/bin/env python

r"""
 _____ ___  ____   ___    _____           _
|_   _/ _ \|  _ \ / _ \  |_   _|__   ___ | |___
  | || | | | | | | | | |   | |/ _ \ / _ \| / __|
  | || |_| | |_| | |_| |   | | (_) | (_) | \__ \
  |_| \___/|____/ \___/    |_|\___/ \___/|_|___/

"""

import argparse
import os
import stat
import sys

import todo_tools

# python2 compat
if sys.version_info[0] == 2:
    input = raw_input


def main():
    args = get_args()

    if args.install_to_bashrc:
        bashrcfilename = os.path.join(os.path.expanduser('~/.bashrc'))
        todo_tools.add_line_to_file_if_not_exists(bashrcfilename,
                                                  'todo -c', '\ntodo -c\n')
    elif args.clear_todos:
        sure = input("Clear the todo file? (y/N) ").lower()
        if sure == 'y':
            open(args.file, 'w').close()
    elif args.check:
        todo_tools.run_as_checker(args)
    elif args.repo_dir:
        if not os.path.isdir(os.path.join(args.repo_dir, '.git')):
            print("Target dir does not appear to be a git repository")
            return 1
        hookfilename = os.path.join(args.repo_dir, '.git/hooks/post-commit')
        todo_tools.add_line_to_file_if_not_exists(
            hookfilename, 'todo', '#!/bin/bash\n\ntodo\n')

        # https://stackoverflow.com/questions/12791997/how-do-you-do-a-simple-chmod-x-from-within-python
        # TL;DR chmod +x hookfile
        file_stats = os.stat(hookfilename)
        os.chmod(hookfilename, file_stats.st_mode | stat.S_IEXEC)
    else:
        sys.stdin = open('/dev/tty')
        todo_tools.run_as_hook(args.file)


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--register-git-hook', metavar='REPO_DIR',
                        dest='repo_dir',
                        help=('Install post-commit hook to git '
                              'repositor(y|ies).'))
    parser.add_argument('-f', '--file', type=str,
                        default=os.path.join(os.path.expanduser('~/.todo')),
                        help=('What file to use as our todo file.'))
    parser.add_argument('-c', '--check', action='store_true', default=False,
                        help=('Check outstanding TODOs and alert '
                              'if any are overdue'))
    parser.add_argument('--clear-todos', action='store_true', default=False,
                        help='Clear TODO file. Warning, cannot be undone.')
    parser.add_argument('--install-to-bashrc', action='store_true',
                        default=False,
                        help='Install automatic checker to .bashrc.')
    args = parser.parse_args()
    # create the todo file if it doesn't exist
    args.file = os.path.abspath(args.file)
    if not os.path.isfile(args.file):
        open(args.file, 'w').close()
    return args


if __name__ == '__main__':
    sys.exit(main())
