#!/usr/bin/env bash
# First-time setup on Ubuntu 26. Run as root from the project root:
#   bash deploy/install.sh
set -euo pipefail

APP_DIR=/var/www/helpdesk
UPLOAD_DIR=/var/lib/helpdesk/uploads
LOG_DIR=/var/log/helpdesk

echo "==> Installing packages"
apt-get update
apt-get install -y apache2 mysql-server \
    php-fpm php-mysql php-mbstring php-curl php-xml php-fileinfo \
    libapache2-mod-xsendfile certbot python3-certbot-apache

echo "==> Enabling Apache modules"
a2enmod rewrite headers proxy_fcgi setenvif xsendfile ssl
a2enconf "php$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')-fpm" || true

echo "==> Creating directories"
mkdir -p "$UPLOAD_DIR" "$LOG_DIR"
chown -R www-data:www-data "$UPLOAD_DIR" "$LOG_DIR"
chmod 750 "$UPLOAD_DIR"

echo "==> Checking the clock (TOTP fails if this drifts)"
timedatectl set-ntp true
timedatectl status | grep -E 'System clock|NTP service'

echo
echo "Remaining manual steps:"
echo "  1. mysql < database/schema.sql"
echo "  2. Create the DB user and grant it access to the helpdesk database"
echo "  3. cp api/config/config.sample.php api/config/config.php and edit it"
echo "  4. php bin/genkey.php    # paste the result into app_key"
echo "  5. cp deploy/99-helpdesk.ini /etc/php/*/fpm/conf.d/ && systemctl restart php*-fpm"
echo "  6. cp deploy/helpdesk.conf /etc/apache2/sites-available/ && a2ensite helpdesk && systemctl reload apache2"
echo "  7. cp deploy/helpdesk.cron /etc/cron.d/helpdesk"
echo "  8. certbot --apache -d helpdesk.example.co.il"
echo "  9. cd web && npm install && npm run build"
echo " 10. php bin/create_admin.php \"Name\" you@example.co.il 'password'"
echo " 11. php bin/selftest.php   # confirms TOTP works on this machine"
