#!/usr/bin/env python3
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/bin/',
        help='The location of where this script should go (default is $HOME/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 = """#!/usr/bin/env python3
import subprocess
import os
import argparse
from argparse import RawTextHelpFormatter
from logger_slg import init_logger


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')

    args = parser.parse_args()

    return args


if __name__ == '__main__':
    logger = init_logger(
        name=__name__,
        log_path=f'/var/log/slg/{__file__.split(\\"/\\")[-1]}.log'
    )

    args = get_arguments()
    print(args)
"""


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}\" > {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}"')
