#!/bin/bash

# --- FARBY PRE TERMINÁL ---
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}==========================================${NC}"
echo -e "${BLUE}   JETOMIT_BIO - AUTOMATICKÝ DEPLOY      ${NC}"
echo -e "${BLUE}==========================================${NC}"

# 1. ZBER ÚDAJOV
read -p "Zadaj svoju doménu (napr. jetomit.bio): " DOMAIN
read -p "Zadaj svoj e-mail (pre SSL/Certbot): " EMAIL
read -p "Vlož svoj RESEND_API_KEY: " RESEND_KEY

# 2. INŠTALÁCIA SYSTÉMOVÝCH BALÍKOV
echo -e "\n${YELLOW}📦 Inštalujem Nginx, Node.js a Certbot...${NC}"
sudo apt update
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs nginx certbot python3-certbot-nginx

# 3. PRÍPRAVA APLIKÁCIE
echo -e "${GREEN}📦 Inštalujem NPM balíky a buildujem projekt...${NC}"
npm install
npm run build

# 4. NASTAVENIE .env
echo -e "${GREEN}🔑 Vytváram .env súbor...${NC}"
echo "RESEND_API_KEY=$RESEND_KEY" > .env
echo "NEXT_PUBLIC_DOMAIN=$DOMAIN" >> .env

# 5. AUTOMATICKÁ KONFIGURÁCIA NGINX
echo -e "${GREEN}🌐 Konfigurujem Nginx pre doménu $DOMAIN...${NC}"

NGINX_CONF="/etc/nginx/sites-available/$DOMAIN"

# Vytvorenie konfiguračného súboru pre Nginx
sudo bash -c "cat <<EOF > $NGINX_CONF
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF"

# Aktivácia konfigurácie a reštart Nginxu
sudo ln -sf $NGINX_CONF /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl restart nginx

# 6. AUTOMATICKÉ SSL (HTTPS)
echo -e "${YELLOW}🔒 Spúšťam Certbot pre automatické SSL...${NC}"
# Certbot sám upraví Nginx konfig a pridá SSL certifikáty
sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN --non-interactive --agree-tos -m $EMAIL --redirect

# 7. NASTAVENIE PM2 (Proces manažér)
echo -e "${GREEN}🚀 Spúšťam aplikáciu cez PM2, aby bežala nonstop...${NC}"
sudo npm install -g pm2
pm2 delete jetomit-bio 2>/dev/null || true
pm2 start npm --name "jetomit-bio" -- start
pm2 save
pm2 startup | bash

echo -e "\n${BLUE}==========================================${NC}"
echo -e "${GREEN}✅ HOTOVO! Tvoj web je live na: https://$DOMAIN${NC}"
echo -e "${BLUE}==========================================${NC}"