#!/usr/bin/env bash
#
# First-time installation on Ubuntu 22.04 / 24.04. Run as root from the project directory:
#
#   sudo DOMAIN=bot.example.com bash scripts/install.sh
#
# The script is idempotent. It installs packages, creates the unix user, fixes
# permissions, generates APP_KEY, migrates and seeds, and installs the Nginx / PHP-FPM /
# Supervisor / cron configuration. It does NOT create the MySQL database or the SSL
# certificate, and it never puts secrets on a command line — see docs/installation.md.

set -euo pipefail

APP_DIR="${APP_DIR:-/var/www/gostardeh}"
APP_USER="${APP_USER:-gostardeh}"
PHP_VERSION="${PHP_VERSION:-8.3}"
DOMAIN="${DOMAIN:-bot.example.com}"

if [[ $EUID -ne 0 ]]; then
    echo "Run as root (sudo)." >&2
    exit 1
fi
if [[ ! -f "$APP_DIR/bin/console" ]]; then
    echo "Project not found in $APP_DIR. Copy the code there first (or set APP_DIR)." >&2
    exit 1
fi

echo "==> Packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y software-properties-common ca-certificates curl unzip
if ! apt-cache show "php${PHP_VERSION}-fpm" >/dev/null 2>&1; then
    add-apt-repository -y ppa:ondrej/php
    apt-get update -y
fi
apt-get install -y \
    "php${PHP_VERSION}-cli" "php${PHP_VERSION}-fpm" "php${PHP_VERSION}-mysql" "php${PHP_VERSION}-curl" \
    "php${PHP_VERSION}-mbstring" "php${PHP_VERSION}-bcmath" "php${PHP_VERSION}-xml" "php${PHP_VERSION}-opcache" \
    nginx redis-server supervisor mysql-client

echo "==> User and permissions"
id -u "$APP_USER" >/dev/null 2>&1 || useradd --system --home "$APP_DIR" --shell /usr/sbin/nologin "$APP_USER"
mkdir -p "$APP_DIR"/storage/{logs,cache,backups,exports}
chown -R "$APP_USER":"$APP_USER" "$APP_DIR"
find "$APP_DIR" -type d -exec chmod 750 {} +
find "$APP_DIR" -type f -exec chmod 640 {} +
chmod 750 "$APP_DIR/bin/console" "$APP_DIR"/scripts/*.sh
chmod 700 "$APP_DIR/storage/backups"
# Nginx only needs to enter public/
usermod -a -G "$APP_USER" www-data
chmod 750 "$APP_DIR/public"

echo "==> Environment"
if [[ ! -f "$APP_DIR/.env" ]]; then
    cp "$APP_DIR/.env.example" "$APP_DIR/.env"
    sed -i "s#^APP_URL=.*#APP_URL=https://${DOMAIN}#" "$APP_DIR/.env"
    chown "$APP_USER":"$APP_USER" "$APP_DIR/.env"
    echo "    .env created — edit it (database, bot token, gateways) and run this script again."
fi
chmod 600 "$APP_DIR/.env"
if ! grep -qE '^APP_KEY=.+' "$APP_DIR/.env"; then
    sudo -u "$APP_USER" "php${PHP_VERSION}" "$APP_DIR/bin/console" key:generate
fi

echo "==> Redis"
systemctl enable --now redis-server

echo "==> Database"
if sudo -u "$APP_USER" "php${PHP_VERSION}" "$APP_DIR/bin/console" migrate --seed; then
    echo "    migrations applied"
else
    echo "    migration failed — create the database and fill DB_* in .env (docs/installation.md), then re-run." >&2
    exit 1
fi

echo "==> PHP-FPM, Nginx, Supervisor, cron"
sed "s#php8\.3#php${PHP_VERSION}#g" "$APP_DIR/deploy/php/gostardeh-fpm.conf" > "/etc/php/${PHP_VERSION}/fpm/pool.d/gostardeh.conf"
systemctl restart "php${PHP_VERSION}-fpm"

if [[ ! -f /etc/nginx/sites-available/gostardeh.conf ]]; then
    sed -e "s#bot\.example\.com#${DOMAIN}#g" -e "s#php8\.3#php${PHP_VERSION}#g" \
        "$APP_DIR/deploy/nginx/gostardeh.conf" > /etc/nginx/sites-available/gostardeh.conf
    echo "    Nginx site written but NOT enabled: obtain the certificate first (docs/installation.md §SSL), then:"
    echo "    ln -s /etc/nginx/sites-available/gostardeh.conf /etc/nginx/sites-enabled/ && nginx -t && systemctl reload nginx"
fi

sed "s#/usr/bin/php #/usr/bin/php${PHP_VERSION} #g" "$APP_DIR/deploy/supervisor/gostardeh.conf" > /etc/supervisor/conf.d/gostardeh.conf
supervisorctl reread
supervisorctl update

sed "s#/usr/bin/php #/usr/bin/php${PHP_VERSION} #g" "$APP_DIR/deploy/cron/gostardeh" > /etc/cron.d/gostardeh
chmod 644 /etc/cron.d/gostardeh

echo
echo "Done. Next steps:"
echo "  1. sudo -u $APP_USER php $APP_DIR/bin/console bot:add          # registers the bot from .env"
echo "  2. sudo -u $APP_USER php $APP_DIR/bin/console webhook:set"
echo "  3. sudo -u $APP_USER php $APP_DIR/bin/console health:check"
