#!/usr/bin/env bash
# =============================================================================
# GYM Locker Management System — VPS Server Setup Script
# =============================================================================
# Run as root (or with sudo) on a fresh Ubuntu 22.04 LTS server.
#
# Usage:
#   chmod +x server-setup.sh
#   sudo ./server-setup.sh
#
# What this script does:
#   1. Updates system packages
#   2. Installs Nginx
#   3. Installs PHP 8.2 + required extensions
#   4. Installs Composer
#   5. Installs MySQL 8.0
#   6. Installs Node.js 20 + npm
#   7. Creates deploy user with SSH key slot
#   8. Creates directory structure for backend + frontend
#   9. Copies Nginx config and enables site
#  10. Installs Certbot for SSL (Let's Encrypt)
#  11. Configures firewall (UFW)
# =============================================================================

set -euo pipefail

# ── Colour helpers ────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()    { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error()   { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# ── Variables — EDIT THESE BEFORE RUNNING ────────────────────────────────────
DOMAIN="yourdomain.com"           # e.g. gymlocker.com
API_DOMAIN="api.yourdomain.com"   # e.g. api.gymlocker.com
DEPLOY_USER="deploy"              # Linux user GitHub Actions SSH into
BACKEND_PATH="/var/www/gymlocker/backend"
FRONTEND_PATH="/var/www/gymlocker/frontend"
DB_NAME="gymlocker"
DB_USER="gymlocker"
DB_PASS="$(openssl rand -base64 24)"   # auto-generated strong password

# =============================================================================
info "Step 1 — Updating system packages..."
# =============================================================================
apt-get update -y
apt-get upgrade -y
apt-get install -y curl wget git unzip zip software-properties-common ufw

# =============================================================================
info "Step 2 — Installing Nginx..."
# =============================================================================
apt-get install -y nginx
systemctl enable nginx
systemctl start nginx

# =============================================================================
info "Step 3 — Installing PHP 8.2 and extensions..."
# =============================================================================
add-apt-repository ppa:ondrej/php -y
apt-get update -y
apt-get install -y \
    php8.2-fpm php8.2-cli php8.2-common \
    php8.2-mysql php8.2-mbstring php8.2-xml \
    php8.2-curl php8.2-zip php8.2-bcmath \
    php8.2-gd php8.2-intl php8.2-redis \
    php8.2-tokenizer php8.2-fileinfo

systemctl enable php8.2-fpm
systemctl start php8.2-fpm

# Tune PHP-FPM for production
PHP_INI="/etc/php/8.2/fpm/php.ini"
sed -i 's/^upload_max_filesize.*/upload_max_filesize = 32M/'  "$PHP_INI"
sed -i 's/^post_max_size.*/post_max_size = 32M/'              "$PHP_INI"
sed -i 's/^memory_limit.*/memory_limit = 256M/'               "$PHP_INI"
sed -i 's/^max_execution_time.*/max_execution_time = 60/'     "$PHP_INI"

# =============================================================================
info "Step 4 — Installing Composer..."
# =============================================================================
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
composer --version

# =============================================================================
info "Step 5 — Installing MySQL 8.0..."
# =============================================================================
apt-get install -y mysql-server
systemctl enable mysql
systemctl start mysql

# Secure MySQL and create database + user
mysql -u root <<SQL
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${DB_PASS}_root';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost','127.0.0.1','::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;

CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost';
FLUSH PRIVILEGES;
SQL

info "MySQL credentials:"
echo "  DB_NAME: ${DB_NAME}"
echo "  DB_USER: ${DB_USER}"
echo "  DB_PASS: ${DB_PASS}"
echo ""
warn "SAVE THESE CREDENTIALS — you will need them for your Laravel .env file!"
echo ""

# =============================================================================
info "Step 6 — Installing Node.js 20..."
# =============================================================================
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
node --version
npm --version

# =============================================================================
info "Step 7 — Creating deploy user..."
# =============================================================================
if ! id -u "${DEPLOY_USER}" &>/dev/null; then
    useradd -m -s /bin/bash "${DEPLOY_USER}"
    usermod -aG www-data "${DEPLOY_USER}"
    info "User '${DEPLOY_USER}' created."
else
    warn "User '${DEPLOY_USER}' already exists — skipping."
fi

# Create .ssh directory for the deploy user
DEPLOY_HOME="/home/${DEPLOY_USER}"
mkdir -p "${DEPLOY_HOME}/.ssh"
chmod 700 "${DEPLOY_HOME}/.ssh"
touch "${DEPLOY_HOME}/.ssh/authorized_keys"
chmod 600 "${DEPLOY_HOME}/.ssh/authorized_keys"
chown -R "${DEPLOY_USER}:${DEPLOY_USER}" "${DEPLOY_HOME}/.ssh"

# Allow deploy user to restart PHP-FPM and set permissions without password
SUDOERS_FILE="/etc/sudoers.d/${DEPLOY_USER}"
cat > "${SUDOERS_FILE}" <<EOF
${DEPLOY_USER} ALL=(ALL) NOPASSWD: /bin/systemctl restart php8.2-fpm
${DEPLOY_USER} ALL=(ALL) NOPASSWD: /bin/chown -R www-data\:www-data /var/www/gymlocker
${DEPLOY_USER} ALL=(ALL) NOPASSWD: /bin/chmod -R 775 /var/www/gymlocker/backend/storage
${DEPLOY_USER} ALL=(ALL) NOPASSWD: /bin/chmod -R 775 /var/www/gymlocker/backend/bootstrap/cache
EOF
chmod 440 "${SUDOERS_FILE}"

info "Deploy user sudoers written to ${SUDOERS_FILE}"

# =============================================================================
info "Step 8 — Creating directory structure..."
# =============================================================================
mkdir -p "${BACKEND_PATH}"
mkdir -p "${FRONTEND_PATH}"

# Make deploy user the owner so GitHub Actions can write here
chown -R "${DEPLOY_USER}:www-data" /var/www/gymlocker
chmod -R 755 /var/www/gymlocker

# =============================================================================
info "Step 9 — Cloning the repository (first time)..."
# =============================================================================
warn "You need to clone your repo manually as the deploy user AFTER adding the"
warn "deploy SSH key to your GitHub repo (Settings → Deploy keys)."
echo ""
echo "Run these commands after this script finishes:"
echo "  su - ${DEPLOY_USER}"
echo "  ssh-keygen -t ed25519 -C 'deploy@${DOMAIN}' -f ~/.ssh/id_ed25519 -N ''"
echo "  cat ~/.ssh/id_ed25519.pub   # add this as a Deploy Key on GitHub"
echo "  git clone git@github.com:kaziramjan/gym-locker-management.git /var/www/gymlocker/repo"
echo "  # Then copy backend/ and frontend/ into the paths above"
echo ""

# =============================================================================
info "Step 10 — Installing Certbot (Let's Encrypt SSL)..."
# =============================================================================
apt-get install -y certbot python3-certbot-nginx

info "SSL certificates will be obtained after Nginx is configured."
warn "Run this AFTER pointing your DNS to this server:"
echo "  certbot --nginx -d ${DOMAIN} -d www.${DOMAIN} -d ${API_DOMAIN}"
echo ""

# =============================================================================
info "Step 11 — Configuring UFW firewall..."
# =============================================================================
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 'Nginx Full'
ufw --force enable
ufw status verbose

# =============================================================================
info "Step 12 — Copying Nginx config..."
# =============================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NGINX_CONF="${SCRIPT_DIR}/nginx.conf"

if [[ -f "${NGINX_CONF}" ]]; then
    # Replace placeholder domain names with actual values
    sed \
        -e "s/yourdomain\.com/${DOMAIN}/g" \
        -e "s/api\.yourdomain\.com/${API_DOMAIN}/g" \
        -e "s|/var/www/gymlocker/backend|${BACKEND_PATH}|g" \
        -e "s|/var/www/gymlocker/frontend|${FRONTEND_PATH}|g" \
        "${NGINX_CONF}" > "/etc/nginx/sites-available/gymlocker"

    ln -sf /etc/nginx/sites-available/gymlocker /etc/nginx/sites-enabled/gymlocker
    rm -f /etc/nginx/sites-enabled/default

    nginx -t && systemctl reload nginx
    info "Nginx config installed and reloaded."
else
    warn "nginx.conf not found at ${NGINX_CONF} — skipping Nginx config."
    warn "Copy deploy/nginx.conf to /etc/nginx/sites-available/gymlocker manually."
fi

# =============================================================================
info "Setup complete!"
# =============================================================================
echo ""
echo "========================================================="
echo "  GYM Locker Management — Server Setup Complete"
echo "========================================================="
echo ""
echo "  Domain:       ${DOMAIN}"
echo "  API Domain:   ${API_DOMAIN}"
echo "  Backend path: ${BACKEND_PATH}"
echo "  Frontend path:${FRONTEND_PATH}"
echo ""
echo "  MySQL:"
echo "    DB_NAME: ${DB_NAME}"
echo "    DB_USER: ${DB_USER}"
echo "    DB_PASS: ${DB_PASS}"
echo ""
echo "  NEXT STEPS:"
echo "  1. Add deploy SSH public key to GitHub repo as Deploy Key"
echo "  2. Clone repo into /var/www/gymlocker/"
echo "  3. Set up Laravel .env (see above DB creds)"
echo "  4. Run: php artisan migrate --seed"
echo "  5. Point DNS A records to this server's IP"
echo "  6. Run: certbot --nginx -d ${DOMAIN} -d www.${DOMAIN} -d ${API_DOMAIN}"
echo "  7. Add GitHub Secrets (see DEPLOY.md)"
echo "  8. Push to main branch — auto-deploy will kick in!"
echo ""
echo "========================================================="
