#!/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()

    # 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 bash

# ARGUMENTS SECTION
# a_flag=''
# b_flag=''
# files=''
# verbose='false'

# print_usage() {
#     printf "Usage: ..."
# }

# while getopts 'abf:v' flag; do
#     case "${flag}" in
#     a) a_flag='true' ;;
#     b) b_flag='true' ;;
#     f) files="${OPTARG}" ;;
#     v) verbose='true' ;;
#     *) print_usage
#         exit 1 ;;
#     esac
# done

args="$@"

"""


if __name__ == '__main__':
    try:
        args = get_arguments()
        script_name = args.script_name
        logger = init_logger(
            name=__name__,
            log_path=f'/var/log/slg/{__file__.split("/")[-1]}.log',
        )
        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}"')
