#!python
import subprocess
import os
import argparse
from logger_slg import init_logger

def get_arguments():
    parser = argparse.ArgumentParser()

    # argument groups can have their tickers combined (ie -su)
    bools = parser.add_argument_group()

    # REQUIRED string value
    parser.add_argument('script_name', help="Name of the script")

    parser.add_argument(
        '-d', '--directory', default='$HOME/.local/bin/',
        help='The location of where this script should go (default is $HOME/.local/bin')

    # optional string value
    parser.add_argument('-u', '--username', default="steven",
                        help="Name of the user")

    bools.add_argument(
        '-nx', dest="make_executable", action="store_false",
        help="By default, we make the script executable. Use this ticker to not make the script executable")

    args = parser.parse_args()

    return args


TEMPLATE = lambda script_name: f"""#!/usr/bin/env python3
import subprocess
import os
import argparse
from argparse import RawTextHelpFormatter
from logger_slg import init_logger
import yaml
from pprint import pformat


def get_arguments():
    parser = argparse.ArgumentParser(description='', formatter_class=RawTextHelpFormatter)

    # argument groups can have their tickers combined (ie -su)
    bools = parser.add_argument_group()

    # REQUIRED string value
    parser.add_argument('arg', help='first argument')

    # integer value
    parser.add_argument('-m', '--max', default=136, type=int,
                        help='')

    # boolean (default=False; store_true means if ticked then args['true'] == True)
    bools.add_argument('-t', dest='true', action='store_true',
                       help='Do you want this to be true? If so, add it with -t')

    # boolean (default=True; store_false means if ticked then args['false'] == False)
    bools.add_argument('-f', dest='false', action='store_false',
                       help='Do you want this to be false? If so, add it with -f')

    parser.add_argument('-c', '--config_filepath', default='/home/steven/.config/slg/{script_name}.yml',
                        help='Filepath of the config file we are using')

    args = parser.parse_args()

    return args

def read_config_file(filepath):
    try:
        with open(filepath, 'r') as stream:
            try:
                config = yaml.safe_load(stream)
                logger.info(f'\\nUsing config:\\n\\n{{pformat(config)}}\\n')
                return config
            except yaml.YAMLError as exc:
                print(exc)
    except FileNotFoundError:
        logger.exception('Config file not found. Proceeding with defaults')


if __name__ == '__main__':
    args = get_arguments()
    print(args)

    try:
        logger = init_logger(
            name=__name__,
            log_path=f'/var/log/slg/{{__file__.split(\\"/\\")[-1]}}.log'
        )
        config = read_config_file(args.config_filepath)

    except:
        logger.exception('An error occurred')
"""


if __name__ == "__main__":
    args = get_arguments()
    script_name = args.script_name
    logger = init_logger(
        name=__name__,
        log_path=f'/var/log/slg/{__file__.split("/")[-1]}.log',
    )
    try:
        result = subprocess.check_output(f"sudo -u {args.username} echo \"{TEMPLATE(script_name)}\" > '{args.directory}/{script_name}'", shell=True)

        # this line makes sure that it ran properly; otherwise it will error out quietly
        logger.info(result)

        if args.make_executable:
            result = subprocess.check_output(
                f"sudo -u {args.username} chmod u+x '{args.directory}/{script_name}'",
                shell=True)
            logger.info(result)

        logger.info(f'Script "{script_name}" successfully created')
    except:
        logger.exception(f'Error occurred while creating script "{script_name}"')
