#!/usr/bin/env bash
set -euo pipefail

if [ "${EUID}" -ne 0 ]; then echo "require root"; exit 1; fi

. /etc/os-release || true
CODENAME=${VERSION_CODENAME:-}
VERSION=${VERSION_ID:-}

apt-get update -y
apt-get install -y python3 python3-venv python3-pip nginx git ffmpeg rsync curl gnupg

if ! command -v mongod >/dev/null 2>&1; then
  if [ -n "$CODENAME" ]; then
    curl -fsSL https://pgp.mongodb.com/server-7.0.asc | gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg || true
    echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu ${CODENAME}/mongodb-org/7.0 multiverse" > /etc/apt/sources.list.d/mongodb-org-7.0.list || true
    apt-get update -y || true
    apt-get install -y mongodb-org || apt-get install -y mongodb
  else
    apt-get install -y mongodb
  fi
  systemctl enable mongod || true
  systemctl start mongod || true
fi

apt-get install -y redis-server
systemctl enable redis-server || true
systemctl start redis-server || true

mkdir -p /srv/taiko-web
SRC_DIR=$(cd "$(dirname "$0")" && pwd)
rsync -a --delete --exclude '.git' --exclude '.venv' "$SRC_DIR/" /srv/taiko-web/

python3 -m venv /srv/taiko-web/.venv
/srv/taiko-web/.venv/bin/pip install -U pip
/srv/taiko-web/.venv/bin/pip install -r /srv/taiko-web/requirements.txt

if [ ! -f /srv/taiko-web/config.py ] && [ -f /srv/taiko-web/config.example.py ]; then
  cp /srv/taiko-web/config.example.py /srv/taiko-web/config.py
fi

chown -R www-data:www-data /srv/taiko-web

cat >/etc/systemd/system/taiko-web.service <<'EOF'
[Unit]
Description=Taiko Web
After=network.target mongod.service redis-server.service

[Service]
Type=simple
WorkingDirectory=/srv/taiko-web
Environment=PYTHONUNBUFFERED=1
ExecStart=/srv/taiko-web/.venv/bin/gunicorn -b 127.0.0.1:8000 app:app
Restart=always
User=www-data
Group=www-data

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable taiko-web
systemctl restart taiko-web

cat >/etc/nginx/sites-available/taiko-web <<'EOF'
server {
    listen 80 default_server;
    server_name _;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://127.0.0.1:8000;
    }
}
EOF

ln -sf /etc/nginx/sites-available/taiko-web /etc/nginx/sites-enabled/taiko-web
rm -f /etc/nginx/sites-enabled/default || true
nginx -t
systemctl restart nginx

if command -v ufw >/dev/null 2>&1; then
  ufw allow 'Nginx Full' || true
fi

echo "ok"