#!/usr/bin/env bash
set -Eeuo pipefail
[[ $EUID -eq 0 ]] || { printf 'Run as root\n' >&2; exit 1; }
ip=${1:?Public IPv4 required}
[[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]
if [[ ! -x /opt/certbot/bin/certbot ]]; then
  python3 -m venv /opt/certbot
  /opt/certbot/bin/pip install 'certbot>=5.4'
fi
/opt/certbot/bin/certbot certonly --dry-run --non-interactive --agree-tos \
  --register-unsafely-without-email --preferred-profile shortlived \
  --webroot --webroot-path /var/www/acme --ip-address "$ip"
/opt/certbot/bin/certbot certonly --non-interactive --agree-tos \
  --register-unsafely-without-email --preferred-profile shortlived \
  --webroot --webroot-path /var/www/acme --ip-address "$ip" \
  --cert-name "$ip" --deploy-hook 'systemctl reload nginx'

python3 - "$ip" <<'PY'
import pathlib
import sys

ip = sys.argv[1]
site = pathlib.Path('/etc/nginx/sites-available/eventcloudai')
config = site.read_text()
if 'ssl_certificate ' not in config:
    config = config.replace('listen 80 default_server;', 'listen 443 ssl default_server;')
    config = config.replace('listen [::]:80 default_server;', 'listen [::]:443 ssl default_server;')
    config = config.replace('    server_name ' + ip + ';', f'''    server_name {ip};
    ssl_certificate /etc/letsencrypt/live/{ip}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{ip}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;''')
    config += f'''
server {{
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name {ip};
    location ^~ /.well-known/acme-challenge/ {{
        root /var/www/acme;
        try_files $uri =404;
    }}
    location / {{ return 301 https://{ip}$request_uri; }}
}}
'''
    site.write_text(config)
env_file = pathlib.Path('/var/www/eventcloudai/shared/.env')
lines = env_file.read_text().splitlines()
changes = {'APP_URL': 'https://' + ip, 'FRONTEND_URL': 'https://' + ip + '/app', 'SESSION_SECURE_COOKIE': 'true'}
env_file.write_text('\n'.join(key + '=' + changes[key] if (key := line.split('=', 1)[0]) in changes else line for line in lines) + '\n')
PY
nginx -t
systemctl reload nginx
if [[ -f /var/www/eventcloudai/current/artisan ]]; then
  cd /var/www/eventcloudai/current
  runuser -u eventcloud -- php artisan config:cache --no-interaction
  /usr/local/sbin/eventcloudai-reload
fi
cat > /etc/systemd/system/eventcloudai-certbot.service <<'EOF'
[Unit]
Description=Renew EventCloudAI HTTPS certificate
[Service]
Type=oneshot
ExecStart=/opt/certbot/bin/certbot renew --quiet
EOF
cat > /etc/systemd/system/eventcloudai-certbot.timer <<'EOF'
[Unit]
Description=Check EventCloudAI certificate twice daily
[Timer]
OnCalendar=*-*-* 00,12:00:00
RandomizedDelaySec=3600
Persistent=true
[Install]
WantedBy=timers.target
EOF
systemctl daemon-reload
systemctl disable --now certbot.timer
systemctl enable --now eventcloudai-certbot.timer
printf 'HTTPS enabled: https://%s/app\n' "$ip"
