#!/usr/bin/env bash
# =============================================================================
# Vibers — server install (Google Cloud VM 136.119.227.200 · https://vibers.codes)
# Tested for Debian 12 and Ubuntu 22.04 / 24.04. Run as root from the project folder:
#
#   sudo bash deploy/install.sh you@email.com
#
# Idempotent: running again updates the code/config and keeps .env, database and data.
# =============================================================================
set -euo pipefail

ACME_EMAIL="${1:-}"
APP_DIR=/var/www/vibers
SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DB_NAME=vibers_main

if [[ $EUID -ne 0 ]]; then echo "Run with sudo."; exit 1; fi
if [[ -z "$ACME_EMAIL" ]]; then echo "Usage: sudo bash deploy/install.sh you@email.com  (e-mail for the HTTPS certificates)"; exit 1; fi

say() { printf '\n\033[1;35m==> %s\033[0m\n' "$*"; }

say "1/9 System packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y ca-certificates curl gnupg lsb-release unzip rsync debian-keyring debian-archive-keyring apt-transport-https

# PHP >= 8.2 (Debian 12 and Ubuntu 24.04 have it; Ubuntu 22.04 needs the ondrej PPA)
. /etc/os-release
if [[ "$ID" == "ubuntu" && "${VERSION_ID%%.*}" -lt 24 ]]; then
  apt-get install -y software-properties-common
  add-apt-repository -y ppa:ondrej/php
  apt-get update -y
  PHPV=8.3
  apt-get install -y php${PHPV}-cli php${PHPV}-fpm php${PHPV}-mysql php${PHPV}-mbstring php${PHPV}-curl php${PHPV}-xml php${PHPV}-intl php${PHPV}-zip
  update-alternatives --set php /usr/bin/php${PHPV} || true
else
  apt-get install -y php-cli php-fpm php-mysql php-mbstring php-curl php-xml php-intl php-zip
  PHPV="$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')"
fi
php -r 'exit(PHP_VERSION_ID >= 80200 ? 0 : 1);' || { echo "PHP 8.2+ required"; exit 1; }
php -r 'exit(function_exists("sodium_crypto_secretbox") ? 0 : 1);' || { echo "PHP sodium missing"; exit 1; }

say "2/9 MariaDB"
apt-get install -y mariadb-server
systemctl enable --now mariadb

say "3/9 Caddy (automatic HTTPS)"
if ! command -v caddy >/dev/null; then
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' > /etc/apt/sources.list.d/caddy-stable.list
  apt-get update -y
  apt-get install -y caddy
fi

say "4/9 System user and files"
id vibers >/dev/null 2>&1 || useradd --system --create-home --home-dir /home/vibers --shell /usr/sbin/nologin vibers
usermod -aG vibers caddy
mkdir -p "$APP_DIR"
rsync -a --delete \
  --exclude '.env' --exclude 'storage/' --exclude '.git/' --exclude '.claude/' --exclude 'tests/' \
  "$SRC_DIR"/ "$APP_DIR"/
mkdir -p "$APP_DIR"/storage/{projects,project_assets,avatars,logs,cache,sessions,backups,temp/preview}
# Bring existing data (projects, images, avatars) when installing from a copy that has them.
if [[ -d "$SRC_DIR/storage" && "$SRC_DIR" != "$APP_DIR" ]]; then
  for d in projects project_assets avatars; do
    [[ -d "$SRC_DIR/storage/$d" ]] && rsync -a --ignore-existing "$SRC_DIR/storage/$d"/ "$APP_DIR/storage/$d"/
  done
fi
chown -R vibers:vibers "$APP_DIR"
find "$APP_DIR" -type d -exec chmod 750 {} +
find "$APP_DIR" -type f -exec chmod 640 {} +
chmod 750 "$APP_DIR"/bin/*.php "$APP_DIR"/deploy/*.sh 2>/dev/null || true

say "5/9 .env and database"
if [[ ! -f "$APP_DIR/.env" ]]; then
  cp "$APP_DIR/deploy/env.production" "$APP_DIR/.env"
  APP_PW="$(openssl rand -hex 24)"; PROV_PW="$(openssl rand -hex 24)"
  KEY="$(php "$APP_DIR/bin/generate-key.php" | cut -d= -f2-)"
  sed -i "s|^APP_KEY=.*|APP_KEY=${KEY}|; s|^DB_PASSWORD=.*|DB_PASSWORD=${APP_PW}|; s|^DB_PROVISIONER_PASSWORD=.*|DB_PROVISIONER_PASSWORD=${PROV_PW}|" "$APP_DIR/.env"
  mysql <<SQL
CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'vibers'@'localhost' IDENTIFIED BY '${APP_PW}';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES, DROP ON \`${DB_NAME}\`.* TO 'vibers'@'localhost';
CREATE USER IF NOT EXISTS 'vibers_provisioner'@'localhost' IDENTIFIED BY '${PROV_PW}';
GRANT CREATE, DROP ON \`sf\_p\_%\`.* TO 'vibers_provisioner'@'localhost';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON \`sf\_p\_%\`.* TO 'vibers_provisioner'@'localhost' WITH GRANT OPTION;
GRANT CREATE USER ON *.* TO 'vibers_provisioner'@'localhost';
FLUSH PRIVILEGES;
SQL
  echo "   .env created with new passwords. Paste your AI and Stripe keys in $APP_DIR/.env afterwards."
fi
chown vibers:vibers "$APP_DIR/.env"; chmod 600 "$APP_DIR/.env"
sudo -u vibers php "$APP_DIR/bin/migrate.php"

say "6/9 PHP-FPM pool"
cp "$APP_DIR/deploy/php-fpm-vibers.conf" "/etc/php/${PHPV}/fpm/pool.d/vibers.conf"
systemctl enable --now "php${PHPV}-fpm"
systemctl restart "php${PHPV}-fpm"

say "7/9 Worker + preview gateway (systemd)"
cp "$APP_DIR"/deploy/systemd/vibers-*.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now vibers-worker vibers-preview
systemctl restart vibers-worker vibers-preview

say "8/9 Caddy config"
mkdir -p /var/log/caddy && chown caddy:caddy /var/log/caddy
cp "$APP_DIR/deploy/Caddyfile" /etc/caddy/Caddyfile
mkdir -p /etc/systemd/system/caddy.service.d
printf '[Service]\nEnvironment=ACME_EMAIL=%s\n' "$ACME_EMAIL" > /etc/systemd/system/caddy.service.d/vibers.conf
systemctl daemon-reload
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
systemctl enable --now caddy
systemctl reload caddy || systemctl restart caddy

say "9/9 Previews and routes for existing projects"
sudo -u vibers php "$APP_DIR/bin/refresh-projects.php" || true

cat <<DONE

 ✅ Vibers installed.
    Platform:  https://vibers.codes
    Previews:  https://preview.vibers.codes/project/{name}/
    Logs:      journalctl -u vibers-worker -f   ·   $APP_DIR/storage/logs/
    Next:      1) put your AI + Stripe keys in $APP_DIR/.env
               2) sudo -u vibers php $APP_DIR/bin/set-role.php you@email.com superadmin   (after signing up)
               3) Stripe webhook → https://vibers.codes/webhooks/stripe
DONE
