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

# Usage:
#   REPO_URL="git@github.com:org/stylunique.git" bash bootstrap-proxmox-ct.sh
# Optional vars:
#   REPO_BRANCH=main
#   APP_USER=stylunique
#   APP_GROUP=stylunique
#   APP_ROOT=/var/www/stylunique
#   NODE_MAJOR=20
#   DOMAIN_STOREFRONT=staging.stylunique.fr
#   DOMAIN_COMMERCE=api-staging.stylunique.fr
#   DOMAIN_CMS=cms-staging.stylunique.fr
#   DB_NAME=stylunique
#   DB_USER=stylunique
#   DB_PASSWORD=change-me
#   ENABLE_CMS=0

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

REPO_URL="${REPO_URL:-}"
REPO_BRANCH="${REPO_BRANCH:-main}"
APP_USER="${APP_USER:-stylunique}"
APP_GROUP="${APP_GROUP:-stylunique}"
APP_ROOT="${APP_ROOT:-/var/www/stylunique}"
NODE_MAJOR="${NODE_MAJOR:-20}"
DOMAIN_STOREFRONT="${DOMAIN_STOREFRONT:-staging.stylunique.fr}"
DOMAIN_COMMERCE="${DOMAIN_COMMERCE:-api-staging.stylunique.fr}"
DOMAIN_CMS="${DOMAIN_CMS:-cms-staging.stylunique.fr}"
DB_NAME="${DB_NAME:-stylunique}"
DB_USER="${DB_USER:-stylunique}"
DB_PASSWORD="${DB_PASSWORD:-change-me}"
ENABLE_CMS="${ENABLE_CMS:-0}"

if [[ -z "${REPO_URL}" ]]; then
  echo "Missing REPO_URL. Example:"
  echo 'REPO_URL="git@github.com:org/stylunique.git" bash bootstrap-proxmox-ct.sh'
  exit 1
fi

echo "[1/11] Installing OS packages..."
apt-get update
apt-get install -y git curl ca-certificates gnupg apache2 postgresql redis-server rsync

echo "[2/11] Installing Node.js ${NODE_MAJOR}..."
mkdir -p /etc/apt/keyrings
if [[ ! -f /etc/apt/keyrings/nodesource.gpg ]]; then
  curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \
    | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
fi
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_${NODE_MAJOR}.x nodistro main" \
  > /etc/apt/sources.list.d/nodesource.list
apt-get update
apt-get install -y nodejs

echo "[3/11] Creating app user and directories..."
getent group "${APP_GROUP}" >/dev/null || groupadd "${APP_GROUP}"
id -u "${APP_USER}" >/dev/null 2>&1 || useradd -m -s /bin/bash -g "${APP_GROUP}" "${APP_USER}"
mkdir -p "${APP_ROOT}" /etc/stylunique/env /var/www/cms-staging
chown -R "${APP_USER}:${APP_GROUP}" "${APP_ROOT}" /var/www/cms-staging

echo "[4/11] Cloning/updating repository..."
if [[ -d "${APP_ROOT}/.git" ]]; then
  su - "${APP_USER}" -c "cd '${APP_ROOT}' && git fetch --all --prune && git checkout '${REPO_BRANCH}' && git pull --ff-only origin '${REPO_BRANCH}'"
else
  rm -rf "${APP_ROOT}"
  su - "${APP_USER}" -c "git clone --branch '${REPO_BRANCH}' '${REPO_URL}' '${APP_ROOT}'"
fi

echo "[5/11] Installing dependencies and building..."
su - "${APP_USER}" -c "cd '${APP_ROOT}' && npm ci && npm run build"

echo "[6/11] Creating environment files..."
if [[ ! -f /etc/stylunique/env/storefront.env ]]; then
  cp "${APP_ROOT}/deploy/staging/linux/env/storefront.env.example" /etc/stylunique/env/storefront.env
fi
if [[ ! -f /etc/stylunique/env/commerce.env ]]; then
  cp "${APP_ROOT}/deploy/staging/linux/env/commerce.env.example" /etc/stylunique/env/commerce.env
fi
if [[ ! -f /etc/stylunique/env/cms.env ]]; then
  cp "${APP_ROOT}/deploy/staging/linux/env/cms.env.example" /etc/stylunique/env/cms.env
fi
chmod 600 /etc/stylunique/env/*.env

sed -i "s|^NEXT_PUBLIC_SITE_URL=.*|NEXT_PUBLIC_SITE_URL=https://${DOMAIN_STOREFRONT}|g" /etc/stylunique/env/storefront.env
sed -i "s|^NEXT_PUBLIC_MEDUSA_BACKEND_URL=.*|NEXT_PUBLIC_MEDUSA_BACKEND_URL=https://${DOMAIN_COMMERCE}|g" /etc/stylunique/env/storefront.env
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgres://$DB_USER:$DB_PASSWORD@127.0.0.1:5432/$DB_NAME|g" /etc/stylunique/env/commerce.env
sed -i "s|^STORE_CORS=.*|STORE_CORS=https://${DOMAIN_STOREFRONT}|g" /etc/stylunique/env/commerce.env
sed -i "s|^ADMIN_CORS=.*|ADMIN_CORS=https://${DOMAIN_COMMERCE},https://${DOMAIN_STOREFRONT}|g" /etc/stylunique/env/commerce.env
sed -i "s|^AUTH_CORS=.*|AUTH_CORS=https://${DOMAIN_STOREFRONT},https://${DOMAIN_COMMERCE}|g" /etc/stylunique/env/commerce.env

echo "[7/11] Creating PostgreSQL role/database..."
systemctl enable --now postgresql
sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${DB_USER}'" | grep -q 1 \
  || sudo -u postgres psql -c "CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASSWORD}';"
sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'" | grep -q 1 \
  || sudo -u postgres psql -c "CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};"

echo "[8/11] Generating systemd services..."
cat >/etc/systemd/system/stylunique-commerce.service <<EOF
[Unit]
Description=Stylunique Commerce (Medusa)
After=network.target postgresql.service redis-server.service
Wants=postgresql.service redis-server.service

[Service]
Type=simple
User=${APP_USER}
Group=${APP_GROUP}
WorkingDirectory=${APP_ROOT}/apps/commerce
EnvironmentFile=/etc/stylunique/env/commerce.env
ExecStart=/bin/sh -lc 'npx medusa db:migrate && npm run start'
Restart=always
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
EOF

cat >/etc/systemd/system/stylunique-storefront.service <<EOF
[Unit]
Description=Stylunique Storefront (Next.js)
After=network.target stylunique-commerce.service
Wants=stylunique-commerce.service

[Service]
Type=simple
User=${APP_USER}
Group=${APP_GROUP}
WorkingDirectory=${APP_ROOT}
EnvironmentFile=/etc/stylunique/env/storefront.env
ExecStart=/usr/bin/npm run start -w @stylunique/storefront -- -p 3000 -H 127.0.0.1
Restart=always
RestartSec=5
KillSignal=SIGINT
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
EOF

echo "[9/11] Generating Apache vhosts..."
a2enmod proxy proxy_http headers rewrite ssl >/dev/null

cat >/etc/apache2/sites-available/${DOMAIN_STOREFRONT}.conf <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN_STOREFRONT}
    ProxyPreserveHost On
    ProxyRequests Off
    RequestHeader set X-Forwarded-Proto "http"
    ProxyPass / http://127.0.0.1:3000/
    ProxyPassReverse / http://127.0.0.1:3000/
    ErrorLog \${APACHE_LOG_DIR}/staging-storefront-error.log
    CustomLog \${APACHE_LOG_DIR}/staging-storefront-access.log combined
</VirtualHost>
EOF

cat >/etc/apache2/sites-available/${DOMAIN_COMMERCE}.conf <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN_COMMERCE}
    ProxyPreserveHost On
    ProxyRequests Off
    RequestHeader set X-Forwarded-Proto "http"
    ProxyPass / http://127.0.0.1:9000/
    ProxyPassReverse / http://127.0.0.1:9000/
    ErrorLog \${APACHE_LOG_DIR}/staging-commerce-error.log
    CustomLog \${APACHE_LOG_DIR}/staging-commerce-access.log combined
</VirtualHost>
EOF

cat >/etc/apache2/sites-available/${DOMAIN_CMS}.conf <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN_CMS}
    DocumentRoot /var/www/cms-staging
    <Directory /var/www/cms-staging>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
    ErrorLog \${APACHE_LOG_DIR}/staging-cms-error.log
    CustomLog \${APACHE_LOG_DIR}/staging-cms-access.log combined
</VirtualHost>
EOF

a2dissite 000-default.conf >/dev/null || true
a2ensite "${DOMAIN_STOREFRONT}.conf" "${DOMAIN_COMMERCE}.conf" "${DOMAIN_CMS}.conf" >/dev/null

echo "[10/11] Enabling services..."
systemctl daemon-reload
systemctl enable --now redis-server
systemctl enable --now stylunique-commerce
systemctl enable --now stylunique-storefront
systemctl restart apache2

if [[ "${ENABLE_CMS}" == "1" ]]; then
  echo "[11/11] Building static CMS..."
  # shellcheck disable=SC1091
  set -a; source /etc/stylunique/env/cms.env; set +a
  su - "${APP_USER}" -c "cd '${APP_ROOT}' && npm run build -w @stylunique/cms"
  rsync -a --delete "${APP_ROOT}/apps/cms/dist/" /var/www/cms-staging/
else
  echo "[11/11] CMS skipped (set ENABLE_CMS=1 to build it)."
fi

echo
echo "Bootstrap done."
echo "Review env files and set real secrets:"
echo "  /etc/stylunique/env/storefront.env"
echo "  /etc/stylunique/env/commerce.env"
echo "Then restart:"
echo "  systemctl restart stylunique-commerce stylunique-storefront apache2"
