#!/bin/bash
# ═══════════════════════════════════════════════════════════════════
# TheKetoBay — ONE COMMAND SETUP
# Kopiraš fajlove na server, pokreneš ovo, i gotovo.
#
# Usage: bash setup-all.sh theketobay.com admin@email.com
# ═══════════════════════════════════════════════════════════════════

DOMAIN=${1:-"theketobay.com"}
EMAIL=${2:-"admin@theketobay.com"}
APP_DIR="/var/www/theketobay.com"

set -e
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
banner() { echo -e "\n${GREEN}▶ $1${NC}"; }
ok()     { echo -e "  ${GREEN}✓ $1${NC}"; }
warn()   { echo -e "  ${YELLOW}! $1${NC}"; }

clear
echo -e "${GREEN}"
cat << 'LOGO'
  ████████╗██╗  ██╗███████╗    ██╗  ██╗███████╗████████╗ ██████╗ ██████╗  █████╗ ██╗   ██╗
     ██╔══╝██║  ██║██╔════╝    ██║ ██╔╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝
     ██║   ███████║█████╗      █████╔╝ █████╗     ██║   ██║   ██║██████╔╝███████║ ╚████╔╝
     ██║   ██╔══██║██╔══╝      ██╔═██╗ ██╔══╝     ██║   ██║   ██║██╔══██╗██╔══██║  ╚██╔╝
     ██║   ██║  ██║███████╗    ██║  ██╗███████╗   ██║   ╚██████╔╝██████╔╝██║  ██║   ██║
     ╚═╝   ╚═╝  ╚═╝╚══════╝    ╚═╝  ╚═╝╚══════╝   ╚═╝    ╚═════╝ ╚═════╝ ╚═╝  ╚═╝   ╚═╝
LOGO
echo -e "${NC}"
echo -e "  🥑 Full-Stack Keto SaaS Platform Setup"
echo -e "  Domain: ${YELLOW}$DOMAIN${NC} | Email: ${YELLOW}$EMAIL${NC}"
echo ""

# Check root
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}❌ Please run as root: sudo bash setup-all.sh${NC}"; exit 1
fi

# Check fajlovi su uploadani
if [ ! -d "$APP_DIR" ]; then
  echo -e "${RED}❌ $APP_DIR not found!${NC}"
  echo "Upload projekt fajlove prvo:"
  echo "  scp theketobay_project.zip root@SERVER_IP:/var/www/"
  echo "  ssh root@SERVER_IP"
  echo "  cd /var/www && unzip theketobay_project.zip && mv theketobay /var/www/theketobay"
  exit 1
fi

cd $APP_DIR

# ── A. System setup ────────────────────────────────────────────────
banner "A. System Update"
apt-get update -qq && apt-get upgrade -y -qq
apt-get install -y -qq curl wget git unzip nano htop ca-certificates gnupg ufw fail2ban openssl
ok "System packages ready"

# ── B. Docker ──────────────────────────────────────────────────────
banner "B. Docker"
if ! command -v docker &>/dev/null; then
  curl -fsSL https://get.docker.com | sh -s -- -q
  systemctl enable docker --quiet && systemctl start docker
  ok "Docker installed"
else
  ok "Docker $(docker --version | cut -d' ' -f3 | tr -d ',')"
fi
ln -sf /usr/libexec/docker/cli-plugins/docker-compose /usr/local/bin/docker-compose 2>/dev/null || true

# ── C. Node.js ─────────────────────────────────────────────────────
banner "C. Node.js 20"
if ! command -v node &>/dev/null || [[ "$(node --version)" != v20* ]]; then
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash - -q
  apt-get install -y -qq nodejs
fi
ok "Node $(node --version)"

# ── D. Firewall ────────────────────────────────────────────────────
banner "D. Firewall"
ufw --force reset
ufw default deny incoming && ufw default allow outgoing
ufw allow 22/tcp && ufw allow 80/tcp && ufw allow 443/tcp
ufw --force enable
ok "UFW: 22, 80, 443 open"

# ── E. Generate secrets ────────────────────────────────────────────
banner "E. Generating Secrets & .env"
if [ ! -f .env ]; then
  cp .env.example .env

  JWT=$(openssl rand -base64 64 | tr -d '\n')
  PGPW=$(openssl rand -base64 18 | tr -d '\n/+=')
  RDPW=$(openssl rand -base64 12 | tr -d '\n/+=')
  MNPW=$(openssl rand -base64 12 | tr -d '\n/+=')

  sed -i "s|CHANGE_ME_STRONG_PASSWORD|$PGPW|g" .env
  sed -i "s|CHANGE_ME_REDIS_PASSWORD|$RDPW|g" .env
  sed -i "s|CHANGE_ME_MINIO_PASSWORD|$MNPW|g" .env
  sed -i "s|CHANGE_ME_VERY_LONG_RANDOM_STRING_AT_LEAST_64_CHARS|$JWT|g" .env
  sed -i "s|https://theketobay.com|https://$DOMAIN|g" .env
  sed -i "s|noreply@theketobay.com|noreply@$DOMAIN|g" .env
  # Update DB connection string
  sed -i "s|ketobay:CHANGE_ME_STRONG_PASSWORD@|ketobay:$PGPW@|g" .env

  ok "Secrets generated"
  warn "STILL NEEDED: Stripe keys + Telegram token in .env"
  echo ""
  echo -e "  ${YELLOW}Open new terminal, edit .env:${NC}"
  echo -e "  ${YELLOW}  nano $APP_DIR/.env${NC}"
  echo ""
  read -p "  Press ENTER after setting STRIPE_SECRET_KEY and TELEGRAM_BOT_TOKEN..."
else
  ok ".env already exists"
fi

mkdir -p infrastructure/db-backup infrastructure/nginx/conf.d

# ── F. Start DB & Redis ────────────────────────────────────────────
banner "F. Starting Infrastructure"
docker compose -f infrastructure/docker-compose.yml up postgres redis minio -d --quiet-pull
echo -n "  Waiting for PostgreSQL"
until docker exec ketobay_db pg_isready -U ketobay -q 2>/dev/null; do echo -n "."; sleep 2; done
ok "PostgreSQL ready"
ok "Redis ready"
ok "MinIO ready"

# ── G. NPM & DB ────────────────────────────────────────────────────
banner "G. Dependencies & Database"
npm install --quiet
ok "npm packages installed"

npx prisma generate --schema=packages/db/prisma/schema.prisma --quiet 2>/dev/null
npx prisma db push --schema=packages/db/prisma/schema.prisma --accept-data-loss 2>/dev/null
ok "Database schema applied"

cd packages/db && npx tsx prisma/seed.ts 2>/dev/null && ok "Database seeded" || warn "Seed skipped"
cd $APP_DIR

# ── H. Build apps ──────────────────────────────────────────────────
banner "H. Building Applications"
npm run build --quiet 2>/dev/null && ok "Apps built" || warn "Build issues — check logs"

# ── I. SSL ─────────────────────────────────────────────────────────
banner "I. SSL Certificate"
echo "  Checking DNS for $DOMAIN..."
SERVER_IP=$(curl -4 -sf ifconfig.me 2>/dev/null || hostname -I | awk '{print $1}')
DOMAIN_IP=$(nslookup $DOMAIN 2>/dev/null | grep -A1 "Name:" | grep "Address:" | tail -1 | awk '{print $2}' || echo "unknown")

if [ "$SERVER_IP" = "$DOMAIN_IP" ]; then
  ok "DNS: $DOMAIN → $SERVER_IP ✓"

  # Get cert
  docker run --rm \
    -v $APP_DIR/infrastructure/certbot/conf:/etc/letsencrypt \
    -p 80:80 \
    certbot/certbot certonly \
    --standalone \
    -d $DOMAIN -d www.$DOMAIN \
    --email $EMAIL \
    --agree-tos --no-eff-email --non-interactive -q \
    && ok "SSL certificate obtained" \
    || warn "SSL failed — run ssl-setup.sh manually after DNS propagates"
else
  warn "DNS not yet pointing to this server ($SERVER_IP)"
  warn "Expected: $DOMAIN → $SERVER_IP, got: $DOMAIN_IP"
  warn "SSL skipped — run: bash infrastructure/ssl-setup.sh $DOMAIN $EMAIL"
fi

# ── J. Start all services ──────────────────────────────────────────
banner "J. Launching Full Stack"
docker compose -f infrastructure/docker-compose.yml up -d --quiet-pull
sleep 8

RUNNING=$(docker compose -f infrastructure/docker-compose.yml ps --services --filter "status=running" 2>/dev/null | wc -l)
ok "$RUNNING services running"

# ── K. Ollama model ────────────────────────────────────────────────
banner "K. Pulling Ollama AI Model"
MODEL=$(grep OLLAMA_MODEL .env | cut -d= -f2 | tr -d '"' || echo "llama3:8b")
echo "  Pulling $MODEL (this may take 5-20 min on first run)..."
docker exec ketobay_ollama ollama pull $MODEL && ok "$MODEL ready" || warn "Pull failed — run: docker exec ketobay_ollama ollama pull $MODEL"

# ── L. Systemd ─────────────────────────────────────────────────────
banner "L. Auto-Start on Reboot"
cat > /etc/systemd/system/theketobay.service << SVCEOF
[Unit]
Description=TheKetoBay
Requires=docker.service
After=docker.service network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$APP_DIR
ExecStart=/usr/bin/docker compose -f infrastructure/docker-compose.yml up -d
ExecStop=/usr/bin/docker compose -f infrastructure/docker-compose.yml down
[Install]
WantedBy=multi-user.target
SVCEOF
systemctl daemon-reload -q && systemctl enable theketobay -q
ok "Auto-start enabled"

# ── M. Cron jobs ───────────────────────────────────────────────────
banner "M. Scheduled Tasks"
(crontab -l 2>/dev/null | grep -v theketobay; \
  echo "0 2 * * * bash $APP_DIR/infrastructure/backup.sh >> /var/log/ketobay-backup.log 2>&1"; \
  echo "0 3 * * * docker run --rm -v $APP_DIR/infrastructure/certbot/conf:/etc/letsencrypt certbot/certbot renew --quiet && docker exec ketobay_nginx nginx -s reload 2>/dev/null"; \
  echo "*/5 * * * * bash $APP_DIR/infrastructure/monitor.sh > /var/log/ketobay-health.log 2>&1" \
) | crontab -
ok "Backup: 2 AM daily"
ok "SSL renewal: 3 AM daily"
ok "Health check: every 5 min"

# ── DONE ──────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   🥑 TheKetoBay is LIVE!                     ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  🌐  https://$DOMAIN"
echo -e "  🔧  https://$DOMAIN/api/health"
echo -e "  👤  admin@theketobay.com  /  Admin123!"
echo ""
echo -e "  ${YELLOW}⚠️  Change admin password immediately!${NC}"
echo -e "  ${YELLOW}⚠️  Set Stripe webhook: https://$DOMAIN/api/payments/webhook${NC}"
echo ""
echo -e "  📋 Useful commands:"
echo -e "     bash $APP_DIR/infrastructure/monitor.sh    # health check"
echo -e "     bash $APP_DIR/infrastructure/update.sh     # deploy updates"
echo -e "     bash $APP_DIR/infrastructure/backup.sh     # manual backup"
echo ""
