#!/usr/bin/env python3
import subprocess
import os
import argparse
import time
from playsound import playsound


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

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

    parser.add_argument('-u', '--username', default='steven',
                        help='The username to be created (default: steven)')

    parser.add_argument('-r', '--remote_ip',
                        help='Remote IP of the machine were connecting to.')

    parser.add_argument('-s', '--sound_file', help='If you wish to include the absolute path to a sound file to alert you when your input is needed. Not all inputs are accounted for.')

    bools.add_argument('-d', '--docker', action='store_true',
                       help='should we install docker?')
    bools.add_argument('-c', '--compose', action='store_true',
                       help='should we install docker-compose?')
    bools.add_argument('-n', '--node', action='store_true',
                       help='should we install node?')

    args = parser.parse_args()

    return args


def verify_location(location):
    input(
        f"This step is meant to be executed on the {location}. Press enter to continue (verify) or Ctrl-C if you're in the wrong location")


if __name__ == '__main__':

    args = get_arguments()
    print(args)

    verify_location('Local machine')
    remote_ip = args.remote_ip if args.remote_ip else input(
        'What is the IP of the remote host? ')

    setup_command = f"""
        adduser {args.username} &&
        usermod -aG sudo {args.username} &&
        mkdir /home/{args.username}/.ssh
    """.replace('\t', '').replace('\n', '')

    # run initial setup commands
    subprocess.run(f'ssh root@{remote_ip} "{setup_command}"', shell=True)

    # copy public ssh key to remote machine
    subprocess.run(
        f"cat ~/.ssh/id_rsa.pub | ssh root@{remote_ip} 'cat >> /home/{args.username}/.ssh/authorized_keys'",
        shell=True)

    # copy github pass protected ssh key to remote machine
    subprocess.run(
        f"cat ~/.ssh/id_rsa | ssh root@{remote_ip} 'cat >> /home/{args.username}/.ssh/id_gh_write_read'",
        shell=True)


    # install fail2ban as root
    cmd = '''
        apt-get install -y fail2ban &&
        cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local &&
        service fail2ban restart
    '''
    subprocess.run(
        f'ssh root@{remote_ip} "{cmd}"',
        shell=True)

    time.sleep(1)
    # remove root login access
    subprocess.run(
        f'''ssh root@{remote_ip} "sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config"''',
        shell=True)

    time.sleep(1)
    if args.sound_file: playsound(args.sound_file)
    password = input('Enter sudo password for user setup: ')
    time.sleep(1)
    user_commands = f'''
        echo {password} | sudo -S apt update &&
        echo {password} | sudo -S apt-get install gcc libpq-dev -y &&
        echo {password} | sudo -S apt-get install python3-dev python3-pip python3-venv python3-wheel -y &&
        pip3 install wheel &&
        pip3 install logger-slg && pip3 install slg_dev_ops &&
        echo {password} | sudo -S mkdir -p /var/log/slg &&
        echo {password} | sudo -S chown -R {args.username}:{args.username} /var/log/slg &&
        echo {password} | sudo -S mkdir -p /var/log/slg/cron &&
        echo {password} | sudo -S chown -R {args.username}:{args.username} /var/log/slg/cron &&
        echo {password} | sudo -S chown -R {args.username}:{args.username} ~/.ssh/ &&
        echo {password} | sudo -S chmod 700 ~/.ssh/ &&
        echo {password} | sudo -S chmod 600 ~/.ssh/*
    '''.replace('\t', '').replace('\n', '')
    subprocess.run(
        f'ssh {args.username}@{remote_ip} "{user_commands}"', shell=True)
    subprocess.run(
        f'ssh {args.username}@{remote_ip} "echo {password} | sudo -S service sshd restart"', shell=True)

    if args.docker:
        cmd = f'''echo {password} | sudo -S apt install -y docker.io &&
                systemctl start docker &&
                systemctl enable docker
                '''
        subprocess.run(
            f'ssh {args.username}@{remote_ip} "{cmd}"', shell=True)
    if args.compose:
        cmd = f'''
            echo {password} | sudo -S curl -L "https://github.com/docker/compose/releases/download/1.29.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose &&
            echo {password} | sudo -S chmod +x /usr/local/bin/docker-compose
        '''
        subprocess.run(
            f'ssh {args.username}@{remote_ip} "{cmd}"', shell=True)
        print('Docker compose successfully installed')

    if args.node:
        cmd = f'''
            echo {password} | sudo -S curl -sL https://deb.nodesource.com/setup_16.x -o /home/{args.username}/nodesource_setup.sh &&
            echo {password} | sudo -S bash nodesource_setup.sh &&
            echo {password} | sudo -S apt-get install -y nodejs
        '''
        subprocess.run(
            f'ssh {args.username}@{remote_ip} "{cmd}"', shell=True)
        print('Node/npm successfully installed')

    # add different git keys as aliases
    lines = '''
    alias gitread="git config --global core.sshCommand 'ssh -i ~/.ssh/id_gh_read_only -F /dev/null'"
    alias gitwrite="git config --global core.sshCommand 'ssh -i ~/.ssh/id_gh_write_read -F /dev/null'"
    '''.replace('\t','')

    # add some additional helping alias
    lines += '''
    alias act="source venv/bin/activate"
    '''.replace('\t', '')

    subprocess.run(
        f"ssh root@{remote_ip} 'echo {lines} >> /home/{args.username}/.bashrc'",
        shell=True)

    print(
        f"\n\nNow you can login as {args.username}: ssh {args.username}@{remote_ip}!")

    if args.docker:
        print("\n\nTo start docker run systemctl start docker && systemctl enable docker")


    # # copy github private ssh key from local machine to /Users/{args.username}/.ssh/ directory
    # print(
    #     f'Copying github private ssh key from local machine to /Users/{args.username}/.ssh/ directory')

    # # install homebrew ( for gh installation )
    # print('Installing homebrew')

    # # install gh (brew install gh)
    # print('Installing gh')

    # # clone repo

    # # run docker compose

    # setup nginx proxy?
