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

APP_DIR="/var/www/html/seniortechventures/seniortech-venture"
SERVICE="seniortechventures.service"
SITE="seniortechventures.conf"
PORT=3019

if [ "$(id -u)" -ne 0 ]; then
  echo "ERRO: execute este script com sudo" >&2
  exit 1
fi
cd "$APP_DIR"
test -s "$APP_DIR/.output/server/index.mjs"
bash "$APP_DIR/scripts/verify-static-assets.sh"
if ! systemctl is-active --quiet "$SERVICE" && ss -ltnH "sport = :$PORT" | grep -q .; then
  echo "ERRO: porta $PORT já está em uso" >&2
  exit 1
fi
if [ -e "/etc/apache2/sites-enabled/$SITE" ]; then
  echo "ERRO: vhost $SITE já existe; revisar antes de substituir" >&2
  exit 1
fi

install -o root -g root -m 0644 "$APP_DIR/ops/seniortechventures.service" "/etc/systemd/system/$SERVICE"
install -o root -g root -m 0644 "$APP_DIR/ops/seniortechventures.conf" "/etc/apache2/sites-available/$SITE"
a2enmod proxy proxy_http
a2ensite "$SITE"
systemctl daemon-reload
systemctl enable --now "$SERVICE"
apache2ctl configtest
systemctl reload apache2

for attempt in $(seq 1 20); do
  if curl --fail --silent --output /dev/null "http://127.0.0.1:$PORT/"; then break; fi
  sleep 1
done
curl --fail --silent --show-error "http://127.0.0.1:$PORT/" -o /dev/null
curl --fail --silent --show-error --resolve seniortechventures.com:80:127.0.0.1 http://seniortechventures.com/ -o /dev/null
for asset in /assets/2024/03/seniortech-logo-1.png /assets/2023/04/favicon-seniortech.png /fonts/montserrat.css /fonts/montserrat-400.ttf; do
  curl --fail --silent --show-error --resolve seniortechventures.com:80:127.0.0.1 "http://seniortechventures.com$asset" -o /dev/null
done
