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

APP_DIR="/var/www/html/ceosclubventures/ceo-ventures"
cd "$APP_DIR"
test -s "$APP_DIR/.output/server/index.mjs"
test -s "$APP_DIR/.output/nitro.json"
test "$(node -e 'process.stdout.write(JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8")).preset)' "$APP_DIR/.output/nitro.json")" = "node-server"
bash "$APP_DIR/scripts/verify-static-assets.sh"
if ! systemctl is-active --quiet ceosclubventures.service && ss -ltnH 'sport = :3017' | grep -q .; then
    echo "ERRO: porta 3017 já está em uso" >&2
    exit 1
fi

install -o root -g root -m 0644 "$APP_DIR/ops/ceosclubventures.service" /etc/systemd/system/ceosclubventures.service
install -o root -g root -m 0644 "$APP_DIR/ops/ceosclub.ventures.conf" /etc/apache2/sites-available/ceosclub.ventures.conf
install -o root -g root -m 0644 "$APP_DIR/ops/ceosclubventures.com.conf" /etc/apache2/sites-available/ceosclubventures.com.conf
install -o root -g root -m 0644 "$APP_DIR/ops/ceosclubventures.com.br.conf" /etc/apache2/sites-available/ceosclubventures.com.br.conf
if [ -s /etc/letsencrypt/live/ceosclub.ventures/fullchain.pem ] && [ -s /etc/letsencrypt/live/ceosclub.ventures/privkey.pem ]; then
    install -o root -g root -m 0644 "$APP_DIR/ops/ceosclub.ventures-le-ssl.conf" /etc/apache2/sites-available/ceosclub.ventures-le-ssl.conf
    install -o root -g root -m 0644 "$APP_DIR/ops/ceosclubventures.com-le-ssl.conf" /etc/apache2/sites-available/ceosclubventures.com-le-ssl.conf
    install -o root -g root -m 0644 "$APP_DIR/ops/ceosclubventures.com.br-le-ssl.conf" /etc/apache2/sites-available/ceosclubventures.com.br-le-ssl.conf
    a2ensite ceosclub.ventures-le-ssl.conf ceosclubventures.com-le-ssl.conf ceosclubventures.com.br-le-ssl.conf
else
    echo "ERRO: certificado TLS CEO's Club não está instalado" >&2
    exit 1
fi
a2enmod proxy proxy_http ssl
a2ensite ceosclub.ventures.conf ceosclubventures.com.conf ceosclubventures.com.br.conf
systemctl daemon-reload
systemctl enable --now ceosclubventures.service
apache2ctl configtest
systemctl reload apache2
curl --fail --silent --show-error http://127.0.0.1:3017/ -o /dev/null
curl --fail --silent --show-error -H 'Host: ceosclub.ventures' http://127.0.0.1/ -o /dev/null
test "$(curl --silent --output /dev/null --write-out '%{http_code}' -H 'Host: ceosclubventures.com' http://127.0.0.1/)" = "301"
test "$(curl --silent --output /dev/null --write-out '%{http_code}' -H 'Host: ceosclubventures.com.br' http://127.0.0.1/)" = "301"
curl --fail --silent --show-error --resolve ceosclub.ventures:443:127.0.0.1 https://ceosclub.ventures/ -o /dev/null
test "$(curl --silent --output /dev/null --write-out '%{http_code}' --resolve ceosclubventures.com:443:127.0.0.1 https://ceosclubventures.com/)" = "301"
test "$(curl --silent --output /dev/null --write-out '%{http_code}' --resolve ceosclubventures.com.br:443:127.0.0.1 https://ceosclubventures.com.br/)" = "301"
