#!/bin/bash
set -euo pipefail
# Run as root: sudo bash /var/www/inat.netviper.com/deploy/install-root.sh
#
# Installs PHP-FPM pool + Apache DocumentRoot for inat.netviper.com on :443,
# creates Postgres DBs inat / inat_test, restarts FPM/Apache.
# TLS: inat.netviper.com is a SAN on the devlib.netviper.com cert.

install -o root -g root -m 644 /var/www/inat.netviper.com/deploy/php-fpm-pool.conf \
  /etc/php/8.3/fpm/pool.d/inat.netviper.com.conf
install -o root -g root -m 644 /var/www/inat.netviper.com/deploy/apache-http.conf \
  /etc/apache2/sites-available/inat.netviper.com.conf
install -o root -g root -m 644 /var/www/inat.netviper.com/deploy/apache-ssl.conf \
  /etc/apache2/sites-available/inat.netviper.com-le-ssl.conf

a2ensite inat.netviper.com inat.netviper.com-le-ssl >/dev/null || true

for db in inat inat_test; do
  if ! sudo -u postgres psql -p 5434 -tAc "SELECT 1 FROM pg_database WHERE datname = '${db}'" | grep -q 1; then
    sudo -u postgres psql -p 5434 -v ON_ERROR_STOP=1 -c "CREATE DATABASE ${db} OWNER viperdev"
    echo "Created database ${db}"
  else
    echo "Database ${db} already exists"
  fi
done

systemctl restart php8.3-fpm
apachectl configtest
systemctl reload apache2

echo "Root deploy complete. Next:"
echo "  1. Edit /var/www/inat.netviper.com/.env → APP_URL=https://inat.netviper.com"
echo "  2. Optionally switch DB_CONNECTION=pgsql DB_DATABASE=inat and php artisan migrate --force"
echo "  3. systemctl --user disable --now inat-mcp-caddy.service inat-mcp-app.service"
echo "  4. curl -sS https://inat.netviper.com/up"
