#!/bin/bash
# =============================================================================
# SEOCheckerPro API — Deployment Script for AlmaLinux 8 / cPanel server
# =============================================================================
# Run as root: bash deploy.sh
#
# What this script does:
#   1. Installs Go 1.21 if not present
#   2. Creates the seocheckerpro system user
#   3. Creates directories and log paths
#   4. Builds the Go binary
#   5. Installs systemd service
#   6. Configures Apache reverse proxy
#   7. Creates the MySQL database and user
#   8. Starts the service
#
# Before running:
#   - Copy .env.example to .env and fill in all values
#   - Make sure api.seocheckerpro.com DNS is pointing to this server
#   - Make sure MySQL root password is available
# =============================================================================

set -euo pipefail

# ── Configuration ─────────────────────────────────────────────────────────────
APP_DIR="/opt/seocheckerpro-api"
APP_USER="seocheckerpro"
LOG_DIR="/var/log/seocheckerpro"
SERVICE_NAME="seocheckerpro-api"
GO_VERSION="1.21.6"
GO_INSTALL_DIR="/usr/local/go"

BLUE='\033[0;34m'
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

log()     { echo -e "${BLUE}[deploy]${NC} $*"; }
success() { echo -e "${GREEN}[done]${NC}   $*"; }
error()   { echo -e "${RED}[error]${NC}  $*"; exit 1; }

# ── Root check ────────────────────────────────────────────────────────────────
if [[ $EUID -ne 0 ]]; then
    error "This script must be run as root"
fi

log "Starting SEOCheckerPro API deployment..."

# ── 1. Install Go ─────────────────────────────────────────────────────────────
if ! command -v go &>/dev/null || [[ "$(go version 2>/dev/null | awk '{print $3}')" != "go${GO_VERSION}" ]]; then
    log "Installing Go ${GO_VERSION}..."
    curl -fsSL "https://golang.org/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz
    rm -rf "${GO_INSTALL_DIR}"
    tar -C /usr/local -xzf /tmp/go.tar.gz
    rm /tmp/go.tar.gz

    # Add to PATH for all users
    cat > /etc/profile.d/golang.sh << 'GOPATH'
export PATH=$PATH:/usr/local/go/bin
export GOPATH=/root/go
GOPATH
    chmod +x /etc/profile.d/golang.sh
    source /etc/profile.d/golang.sh
    success "Go ${GO_VERSION} installed"
else
    success "Go already installed: $(go version)"
fi

export PATH=$PATH:/usr/local/go/bin

# ── 2. System user ────────────────────────────────────────────────────────────
if ! id -u "${APP_USER}" &>/dev/null; then
    log "Creating system user '${APP_USER}'..."
    useradd -r -s /sbin/nologin -d "${APP_DIR}" "${APP_USER}"
    success "User '${APP_USER}' created"
else
    success "User '${APP_USER}' already exists"
fi

# ── 3. Directories ────────────────────────────────────────────────────────────
log "Creating directories..."
mkdir -p "${APP_DIR}"
mkdir -p "${LOG_DIR}"
chown -R "${APP_USER}:${APP_USER}" "${APP_DIR}"
chown -R "${APP_USER}:${APP_USER}" "${LOG_DIR}"
success "Directories created"

# ── 4. Copy source and build ──────────────────────────────────────────────────
log "Copying source files to ${APP_DIR}..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Copy everything except the binary
rsync -a --exclude="*.exe" --exclude="seocheckerpro-api" \
    "${SCRIPT_DIR}/" "${APP_DIR}/"

log "Building Go binary..."
cd "${APP_DIR}"
# Download dependencies
/usr/local/go/bin/go mod download
# Build optimised binary
/usr/local/go/bin/go build \
    -ldflags="-s -w" \
    -o "${APP_DIR}/seocheckerpro-api" \
    ./cmd/server/

chown "${APP_USER}:${APP_USER}" "${APP_DIR}/seocheckerpro-api"
chmod 750 "${APP_DIR}/seocheckerpro-api"
success "Binary built: ${APP_DIR}/seocheckerpro-api"

# ── 5. .env file ──────────────────────────────────────────────────────────────
if [[ ! -f "${APP_DIR}/.env" ]]; then
    if [[ -f "${SCRIPT_DIR}/.env" ]]; then
        cp "${SCRIPT_DIR}/.env" "${APP_DIR}/.env"
    else
        cp "${APP_DIR}/.env.example" "${APP_DIR}/.env"
        echo ""
        echo -e "${RED}WARNING: .env file not found. A template has been copied to ${APP_DIR}/.env${NC}"
        echo "Edit it before starting the service:"
        echo "  nano ${APP_DIR}/.env"
        echo ""
    fi
fi
chown "${APP_USER}:${APP_USER}" "${APP_DIR}/.env"
chmod 600 "${APP_DIR}/.env"

# ── 6. Systemd service ────────────────────────────────────────────────────────
log "Installing systemd service..."
cp "${APP_DIR}/seocheckerpro-api.service" "/etc/systemd/system/${SERVICE_NAME}.service"
systemctl daemon-reload
systemctl enable "${SERVICE_NAME}"
success "Systemd service installed and enabled"

# ── 7. Apache proxy ───────────────────────────────────────────────────────────
log "Configuring Apache reverse proxy..."
cp "${APP_DIR}/apache-proxy.conf" "/etc/httpd/conf.d/seocheckerpro-api.conf"

# Enable required Apache modules
if ! httpd -M 2>/dev/null | grep -q proxy_module; then
    log "Enabling Apache proxy modules..."
    # cPanel/WHM typically uses EasyApache — modules may need to be enabled via WHM
    echo "Note: Please ensure mod_proxy and mod_proxy_http are enabled in WHM → EasyApache"
fi

# Test Apache config
if httpd -t 2>/dev/null; then
    systemctl reload httpd
    success "Apache configured and reloaded"
else
    echo -e "${RED}Apache config test failed — please check /etc/httpd/conf.d/seocheckerpro-api.conf${NC}"
fi

# ── 8. MySQL database setup ───────────────────────────────────────────────────
log "Setting up MySQL database..."
read -rp "Enter MySQL root password: " -s MYSQL_ROOT_PASS
echo ""

# Read DB config from .env
DB_NAME=$(grep "^DB_NAME=" "${APP_DIR}/.env" | cut -d= -f2 | tr -d ' ')
DB_USER=$(grep "^DB_USER=" "${APP_DIR}/.env" | cut -d= -f2 | tr -d ' ')
DB_PASS=$(grep "^DB_PASS=" "${APP_DIR}/.env" | cut -d= -f2 | tr -d ' ')

if [[ -z "$DB_NAME" || -z "$DB_USER" || -z "$DB_PASS" ]]; then
    echo -e "${RED}DB_NAME, DB_USER, or DB_PASS not set in .env — skipping database setup${NC}"
else
    mysql -uroot -p"${MYSQL_ROOT_PASS}" <<SQL
CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASS}';
GRANT SELECT, INSERT, UPDATE, DELETE ON \`${DB_NAME}\`.* TO '${DB_USER}'@'127.0.0.1';
FLUSH PRIVILEGES;
SQL
    success "MySQL database '${DB_NAME}' and user '${DB_USER}' created"
fi

# ── 9. Start service ──────────────────────────────────────────────────────────
log "Starting ${SERVICE_NAME}..."
systemctl start "${SERVICE_NAME}"
sleep 2

if systemctl is-active --quiet "${SERVICE_NAME}"; then
    success "Service is running!"
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "  SEOCheckerPro API deployed successfully"
    echo ""
    echo "  Service:    systemctl status ${SERVICE_NAME}"
    echo "  Logs:       tail -f ${LOG_DIR}/app-current.log"
    echo "  Journal:    journalctl -u ${SERVICE_NAME} -f"
    echo "  Config:     ${APP_DIR}/.env"
    echo "  Health:     curl http://localhost:8080/api/health"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
else
    echo -e "${RED}Service failed to start. Check logs:${NC}"
    echo "  journalctl -u ${SERVICE_NAME} -n 50 --no-pager"
    exit 1
fi
