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

APP_DIR="/var/www/html/alyaventures/alya-ventures"
SERVICE="alyaventures.service"
PORT=3018

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

install -o root -g root -m 0644 "$APP_DIR/ops/alyaventures.service" "/etc/systemd/system/$SERVICE"
install -o root -g root -m 0644 "$APP_DIR/ops/alya.ventures.conf" /etc/apache2/sites-available/alya.ventures.conf
if [ ! -s /etc/letsencrypt/live/alya.ventures/fullchain.pem ] || [ ! -s /etc/letsencrypt/live/alya.ventures/privkey.pem ]; then
  echo "ERRO: certificado TLS de alya.ventures não está instalado" >&2
  exit 1
fi
install -o root -g root -m 0644 "$APP_DIR/ops/alya.ventures-le-ssl.conf" /etc/apache2/sites-available/alya.ventures-le-ssl.conf
a2enmod proxy proxy_http ssl
a2ensite alya.ventures.conf alya.ventures-le-ssl.conf
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
test "$(curl --silent --output /dev/null --write-out '%{http_code}' -H 'Host: alya.ventures' http://127.0.0.1/)" = "301"
curl --fail --silent --show-error --resolve alya.ventures:443:127.0.0.1 https://alya.ventures/ -o /dev/null
curl --fail --silent --show-error --resolve www.alya.ventures:443:127.0.0.1 https://www.alya.ventures/ -o /dev/null
for asset in \
  /assets/logo-alya-ventures-branca.webp \
  /assets/icn-planejamento-estrategico.svg \
  /fonts/7cHpv4kjgoGqM7EPCw.ttf \
  /videos/alya-ventures.mp4 \
  /videos/alya-ventures-poster.webp; do
  curl --fail --silent --show-error --resolve "alya.ventures:443:127.0.0.1" "https://alya.ventures$asset" -o /dev/null
done
