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

if [[ ${EUID} -ne 0 ]]; then
  echo "Run: sudo bash install-ubuntu.sh share.example.com"
  exit 1
fi

DOMAIN="${1:-}"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET_DIR="/opt/relay"

if [[ ! "$DOMAIN" =~ ^([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$ ]]; then
  echo "Use a valid domain name"
  exit 1
fi

apt update
apt install -y ca-certificates curl gnupg build-essential python3 make g++ apache2 certbot python3-certbot-apache
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt install -y nodejs

mkdir -p "$TARGET_DIR"
cp -a "$SOURCE_DIR/." "$TARGET_DIR/"
cd "$TARGET_DIR"

if [[ ! -f package.json ]]; then
  npm init -y >/dev/null 2>&1
fi

npm install --omit=dev express socket.io socket.io-client esbuild
bash build-client.sh

cat > /etc/relay.env <<EOF
PORT=3001
EOF

sed "s/share.example.com/$DOMAIN/g" relay-sfu-apache.conf > /etc/apache2/sites-available/relay.conf
cp relay-sfu.service /etc/systemd/system/relay.service
chown -R www-data:www-data "$TARGET_DIR"
chmod 640 /etc/relay.env
chmod +x "$TARGET_DIR/build-client.sh"
a2enmod proxy proxy_http proxy_wstunnel headers ssl
a2ensite relay.conf
systemctl daemon-reload
systemctl enable --now relay
systemctl reload apache2

if command -v ufw >/dev/null 2>&1; then
  ufw allow 80/tcp
  ufw allow 443/tcp
fi

echo "Relay is running on http://$DOMAIN"
echo "Enable HTTPS now: sudo certbot --apache -d $DOMAIN"
