#!/usr/bin/env python3
from init import *
import argparse
from string import Template


def get_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description='Get certificate with certbot.')
    parser.add_argument('-d', '--domain', type=str, help='The domain name(s) for certificate.')
    parser.add_argument('-t', '--timeout', type=float, default=10, help='The timeout for certbot.')
    parsed_args = parser.parse_args()
    return parsed_args


if __name__ == '__main__':
    args = get_args()

    # https://certbot.eff.org/
    execute('''sudo apt update
sudo apt install -y python3 python3-venv libaugeas0 expect
sudo apt-get remove certbot
sudo python3 -m venv /opt/certbot/
sudo /opt/certbot/bin/pip install --upgrade pip
sudo /opt/certbot/bin/pip install certbot
''')
    execute('sudo ln -s /opt/certbot/bin/certbot /usr/bin/certbot', ignore_error=['File exists'])
    command = 'sudo certbot certonly --standalone'
    if not args.domain:
        execute(command)
    else:
        execute(Template(r"""/usr/bin/expect <<EOF
    set timeout $timeout
    spawn $command
    while {1} {
        expect {
            "Enter email address" {
                send "\r"
            }
            "Please read the Terms of Service" {
                send "Y\r"
            }
            "Please enter the domain" {
                send "$domain\r"
            }
            "Do you want to expand and replace this existing certificate" {
                send "E\r"
            }
            eof {
                break
            }
        }
    }
EOF""").substitute(timeout=args.timeout, command=command, domain=args.domain))

    crontab_command = "0 0,12 * * * root /opt/certbot/bin/python -c 'import random; import time; time.sleep(random.random() * 3600)' && sudo certbot renew -q"
    if crontab_command not in Path('/etc/crontab').read_text():
        execute(f"""echo "{crontab_command}" | sudo tee -a /etc/crontab > /dev/null""")
