#!/usr/bin/env python3
import subprocess
import os
import argparse
from argparse import RawTextHelpFormatter
from logger_slg import init_logger
from colorama import Fore, Back, Style
import requests
import time


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

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

    parser.add_argument('-p', '--project_name', help='Name of the project you are creating', required=True)

    parser.add_argument('-d', '--domain_name', help='Domain name of the site (with no www prepended, ie twitchclip.io)', required=True)

    parser.add_argument('-u', '--username', help='Username to be created on the remote machine', required=True)

    parser.add_argument('-r', '--remote_ip', help='IP address of the remote server', required=True)

    parser.add_argument('-e', '--email_address', help='Email address for LetsEncrypt', required=True)

    args = parser.parse_args()

    return args

def run_remote_command(username, remote_ip, user_commands):
    subprocess.run(
        f'ssh {username}@{remote_ip} "{user_commands}"', shell=True)
    # an example command with sudo access
    # user_commands = f'''
    #     echo {password} | sudo -S apt update &&
    #     echo {password} | sudo -S apt-get install -y python3-pip &&
    #     pip3 install slg-dev-ops &&
    #     echo {password} | sudo -S chown -R {args.username} ~/.ssh/ &&
    #     echo {password} | sudo -S chmod 700 ~/.ssh/ &&
    #     echo {password} | sudo -S chmod 600 ~/.ssh/*
    # '''.replace('\t', '').replace('\n', '')

def run_local_command(command):
    subprocess.run(command, shell=True)

def print_in_color_then_reset(print_string, color=Fore.RED):
    print(color + print_string, flush=True)
    print(Style.RESET_ALL, flush=True)

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

    args = get_arguments()
    print(args)

    uname = args.username
    ip = args.remote_ip

    input('\n ---- Create a digital ocean droplet of Ubuntu 20. Press any key to continue. ---- \n')
    input('\n ---- Apply the firewall "slg-Automated-Website-Firewall" to the droplet. Press any key to continue. ---- \n')
    input('\n ---- Now would also be a good time to point your domain to your IP on your domain hosting site. Press any key to continue. ---- \n')

    print("\n---- NOTE: this script will ask you for your password many times. This is for ease of development and shouldn't be cause for alarm ----\n")

    password = input('Please enter your password for sudo commands and the password of the user to be created: ')


    print_in_color_then_reset('\n\n---- NOW STARTING LINE 70 ----\n\n')
    run_local_command(f'slg-digital-ocean-droplet-setup -r {ip} -u {uname} -dn')

    print_in_color_then_reset('\n\n---- NOW STARTING LINE 73 ----\n\n')
    run_remote_command(uname, ip, f'echo {password} | sudo -S mkdir -p /var/log/slg && echo {password} | sudo -S chown -R {uname}:{uname} /var/log/slg')

    print_in_color_then_reset('\n\n---- NOW STARTING LINE 74 ----\n\n')
    run_remote_command(uname, ip, f'PATH=/home/steven/.local/bin:$PATH; echo {password} | sudo -S -E env "PATH=$PATH" slg-install-nginx')
    print_in_color_then_reset('\n\n---- NOW STARTING LINE 76 ----\n\n')
    run_remote_command(uname, ip, f'PATH=/home/steven/.local/bin:$PATH; echo {password} | sudo -S -E env "PATH=$PATH" slg-install-firewall')
    print_in_color_then_reset('\n\n---- NOW STARTING LINE 78 ----\n\n')
    run_remote_command(uname, ip, f'PATH=/home/steven/.local/bin:$PATH; slg-init-remote-crontab -u {uname}')

    while True:
        try:
            resp = requests.get(f'http://{args.domain_name}')
            if resp.status_code == 200:
                break
            else:
                print("Domain name not ready. Make sure you've pointed the domain name to the new IP.", flush=True)
                print("Trying again in 5 seconds...", flush=True)
                time.sleep(5)
        except:
            print("Domain name not ready. Make sure you've pointed the domain name to the new IP.", flush=True)
            print("Trying again in 5 seconds...", flush=True)
            time.sleep(5)


    print_in_color_then_reset('\n\n---- NOW STARTING LINE 83 ----\n\n')
    run_remote_command(uname, ip, f'echo {password} | sudo -S -E env "PATH=$PATH" slg-setup-tls-ssl-nginx {args.domain_name} -u {uname} -e {args.email_address}')
    print_in_color_then_reset('\n\n---- NOW STARTING LINE 85 ----\n\n')
    run_remote_command(uname, ip, f'echo {password} | sudo -S -E env "PATH=$PATH" slg-init-nginx-conf-gunicorn -f /etc/nginx/conf.d/{args.project_name}.conf -d {args.domain_name},www.{args.domain_name}')
    print_in_color_then_reset('\n\n---- NOW STARTING LINE 87 ----\n\n')
    run_remote_command(uname, ip, f'echo {password} | sudo -S mkdir -p /var/www/html/static')
    print_in_color_then_reset('\n\n---- NOW STARTING LINE 89 ----\n\n')
    run_remote_command(uname, ip, f'echo {password} | sudo -S npm install -g javascript-obfuscator')
    print_in_color_then_reset('\n\n---- NOW STARTING LINE 91 ----\n\n')
    run_remote_command(uname, ip, f'echo {password} | sudo -S docker run -p 27017:27017 -v /home/{uname}/{args.project_name}-mongo:/data/db -d mongo')
