#!/bin/bash
# ============================================================
# Crypto Mining System — Deploy / Update Script
# Run after pulling new code: sudo bash deploy.sh
# ============================================================
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
log()  { echo -e "${GREEN}[✓]${NC} $1"; }
info() { echo -e "${BLUE}[→]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
err()  { echo -e "${RED}[✗]${NC} $1"; exit 1; }

APP_DIR="/opt/crypto-mining"
APP_USER="cryptomining"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"

[[ $EUID -ne 0 ]] && err "Run as root: sudo bash deploy.sh"

echo -e "\n${BLUE}━━━ Deploying Update ━━━${NC}"
echo "Source: ${PROJECT_ROOT}"
echo "Target: ${APP_DIR}"
echo ""

# ── Backend ──────────────────────────────────────────────────
info "Updating backend files..."
rsync -a --exclude='.env' --exclude='venv/' --exclude='logs/' \
    "${PROJECT_ROOT}/backend/" "${APP_DIR}/backend/"
chown -R ${APP_USER}:${APP_USER} ${APP_DIR}/backend

info "Installing new Python dependencies..."
sudo -u ${APP_USER} ${APP_DIR}/backend/venv/bin/pip install -q \
    -r ${APP_DIR}/backend/requirements.txt

info "Restarting backend..."
systemctl restart cryptomining-api
sleep 2

if systemctl is-active --quiet cryptomining-api; then
    log "Backend updated and running"
else
    err "Backend failed — check: journalctl -u cryptomining-api -n 50"
fi

# ── Frontend ─────────────────────────────────────────────────
info "Updating frontend files..."
rsync -a --exclude='node_modules/' --exclude='dist/' \
    "${PROJECT_ROOT}/frontend/" "${APP_DIR}/frontend/"
chown -R ${APP_USER}:${APP_USER} ${APP_DIR}/frontend

info "Installing new npm dependencies..."
cd ${APP_DIR}/frontend
sudo -u ${APP_USER} npm install --silent

info "Building frontend..."
sudo -u ${APP_USER} npm run build
log "Frontend built"

# ── Nginx ────────────────────────────────────────────────────
nginx -t && systemctl reload nginx
log "Nginx reloaded"

echo ""
log "Deployment complete!"
echo -e "  Status: ${BLUE}systemctl status cryptomining-api${NC}"
echo -e "  Logs:   ${BLUE}journalctl -u cryptomining-api -f${NC}"
