#!/bin/bash
# =============================================================================
# Настройка на Хостинг сървър с Cloudflare Tunnel
# Автор: Федя Серафиев | itpraktika.com
# =============================================================================

set -euo pipefail

# ── Цветове ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'

info()    { echo -e "${CYAN}ℹ️  $*${RESET}"; }
success() { echo -e "${GREEN}✅ $*${RESET}"; }
warn()    { echo -e "${YELLOW}⚠️  $*${RESET}"; }
error()   { echo -e "${RED}❌ $*${RESET}" >&2; exit 1; }

# ── Генериране на парола ─────────────────────────────────────────────────────
gen_pass() {
    openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 24
}

# ── Валидация ─────────────────────────────────────────────────────────────────
validate_yn() {
    local val="$1"
    [[ "$val" =~ ^[yYnN]$ ]] || error "Въведи 'y' или 'n'."
}

validate_count() {
    local val="$1"
    [[ "$val" =~ ^[0-2]$ ]] || error "Въведи 0, 1 или 2."
}

# =============================================================================
echo -e "\n${BOLD}════════════════════════════════════════════════════${RESET}"
echo -e "${BOLD}     🚀 Настройка на Хостинг с Cloudflare Tunnel    ${RESET}"
echo -e "${BOLD}════════════════════════════════════════════════════${RESET}\n"

# ── 1. Избор на метод за Cloudflare Tunnel ────────────────────────────────────
echo -e "${BOLD}[1/4] Cloudflare Tunnel — метод на свързване${RESET}"
echo "  1) Token  — въвеждаш готов токен от Cloudflare Dashboard"
echo "  2) Login  — cloudflared се логва сам (ще отвори браузър / URL)"
echo ""
read -rp "Избери метод [1/2]: " cf_method

case "$cf_method" in
  1)
    read -rp "  Въведи Tunnel Token: " cf_token
    [[ -n "$cf_token" ]] || error "Токенът не може да е празен."
    CLOUDFLARED_CMD='tunnel --no-autoupdate run --token ${TUNNEL_TOKEN}'
    CF_ENV_LINE="      - TUNNEL_TOKEN=\${TUNNEL_TOKEN}"
    CF_TOKEN_IN_ENV="TUNNEL_TOKEN=$cf_token"
    ;;
  2)
    info "При стартиране cloudflared ще изведе URL за автентикация."
    CLOUDFLARED_CMD='tunnel --no-autoupdate login'
    CF_ENV_LINE=""
    CF_TOKEN_IN_ENV="# TUNNEL_TOKEN= (използва се login метод)"
    cf_token=""
    ;;
  *)
    error "Невалиден избор. Въведи 1 или 2."
    ;;
esac

# ── 2. Uptime Kuma ────────────────────────────────────────────────────────────
echo -e "\n${BOLD}[2/4] Uptime Kuma${RESET}"
read -rp "Инсталирай Uptime Kuma? (y/n): " install_kuma
validate_yn "$install_kuma"
install_kuma="${install_kuma,,}"   # lowercase

# ── 3. WordPress сайтове ──────────────────────────────────────────────────────
echo -e "\n${BOLD}[3/4] WordPress сайтове${RESET}"
read -rp "Брой WordPress сайтове? (0/1/2): " wp_count
validate_count "$wp_count"

# ── 4. Генериране на пароли ───────────────────────────────────────────────────
echo -e "\n${BOLD}[4/4] Генериране на пароли...${RESET}"
DB_ROOT_PASS=$(gen_pass)
WP1_DB_PASS=$(gen_pass)
WP2_DB_PASS=$(gen_pass)

# =============================================================================
# .env файл
# =============================================================================
cat > .env <<EOF
# ── Cloudflare ────────────────────────────────────────────────────
$CF_TOKEN_IN_ENV

# ── База данни ────────────────────────────────────────────────────
DB_ROOT_PASSWORD=$DB_ROOT_PASS
WP1_DB_PASSWORD=$WP1_DB_PASS
WP2_DB_PASSWORD=$WP2_DB_PASS
EOF
chmod 600 .env
success ".env създаден (права: 600)"

# =============================================================================
# Генериране на init SQL за базите данни
# =============================================================================
mkdir -p db-init

SQL_CONTENT=""
if [[ "$wp_count" -ge 1 ]]; then
  SQL_CONTENT+="CREATE DATABASE IF NOT EXISTS wp1_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n"
  SQL_CONTENT+="CREATE USER IF NOT EXISTS 'wp1_user'@'%' IDENTIFIED BY '${WP1_DB_PASS}';\n"
  SQL_CONTENT+="GRANT ALL PRIVILEGES ON wp1_db.* TO 'wp1_user'@'%';\n"
fi
if [[ "$wp_count" -ge 2 ]]; then
  SQL_CONTENT+="CREATE DATABASE IF NOT EXISTS wp2_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n"
  SQL_CONTENT+="CREATE USER IF NOT EXISTS 'wp2_user'@'%' IDENTIFIED BY '${WP2_DB_PASS}';\n"
  SQL_CONTENT+="GRANT ALL PRIVILEGES ON wp2_db.* TO 'wp2_user'@'%';\n"
fi
SQL_CONTENT+="FLUSH PRIVILEGES;\n"

printf "%b" "$SQL_CONTENT" > db-init/01-init.sql
success "db-init/01-init.sql създаден"

# =============================================================================
# docker-compose.yml
# =============================================================================
cat > docker-compose.yml <<EOF
services:

  # ── Cloudflare Tunnel ───────────────────────────────────────────
  cloudflared:
    image: cloudflare/cloudflared:latest
    restart: always
    command: $CLOUDFLARED_CMD
    networks:
      - internal
EOF

# Добавяне на environment само при token метод
if [[ -n "$CF_ENV_LINE" ]]; then
cat >> docker-compose.yml <<EOF
    environment:
$CF_ENV_LINE
EOF
fi

# ── MariaDB ────────────────────────────────────────────────────────────────
cat >> docker-compose.yml <<EOF

  # ── База данни ──────────────────────────────────────────────────
  db:
    image: mariadb:10.6
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: \${DB_ROOT_PASSWORD}
    volumes:
      - db_data:/var/lib/mysql
      - ./db-init:/docker-entrypoint-initdb.d:ro
    networks:
      - internal
    healthcheck:
      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
      interval: 10s
      timeout: 5s
      retries: 5
EOF

# ── Uptime Kuma ────────────────────────────────────────────────────────────
if [[ "$install_kuma" == "y" ]]; then
cat >> docker-compose.yml <<EOF

  # ── Uptime Kuma ─────────────────────────────────────────────────
  uptime-kuma:
    image: louislam/uptime-kuma:latest
    container_name: uptime-kuma
    restart: always
    volumes:
      - kuma_data:/app/data
    networks:
      - internal
EOF
fi

# ── WordPress 1 ────────────────────────────────────────────────────────────
if [[ "$wp_count" -ge 1 ]]; then
cat >> docker-compose.yml <<EOF

  # ── WordPress 1 ─────────────────────────────────────────────────
  wp1:
    image: wordpress:latest
    restart: always
    depends_on:
      db:
        condition: service_healthy
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: wp1_user
      WORDPRESS_DB_PASSWORD: \${WP1_DB_PASSWORD}
      WORDPRESS_DB_NAME: wp1_db
    volumes:
      - wp1_data:/var/www/html
    networks:
      - internal
EOF
fi

# ── WordPress 2 ────────────────────────────────────────────────────────────
if [[ "$wp_count" -ge 2 ]]; then
cat >> docker-compose.yml <<EOF

  # ── WordPress 2 ─────────────────────────────────────────────────
  wp2:
    image: wordpress:latest
    restart: always
    depends_on:
      db:
        condition: service_healthy
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: wp2_user
      WORDPRESS_DB_PASSWORD: \${WP2_DB_PASSWORD}
      WORDPRESS_DB_NAME: wp2_db
    volumes:
      - wp2_data:/var/www/html
    networks:
      - internal
EOF
fi

# ── Networks & Volumes ─────────────────────────────────────────────────────
cat >> docker-compose.yml <<EOF

networks:
  internal:
    driver: bridge

volumes:
  db_data:
EOF

[[ "$install_kuma" == "y" ]] && echo "  kuma_data:" >> docker-compose.yml
[[ "$wp_count" -ge 1 ]]      && echo "  wp1_data:"  >> docker-compose.yml
[[ "$wp_count" -ge 2 ]]      && echo "  wp2_data:"  >> docker-compose.yml

success "docker-compose.yml създаден"

# =============================================================================
# Резюме
# =============================================================================
echo ""
echo -e "${BOLD}════════════════════════════════════════════════════${RESET}"
echo -e "${BOLD}               📋 Резюме на конфигурацията         ${RESET}"
echo -e "${BOLD}════════════════════════════════════════════════════${RESET}"
echo -e "  Cloudflare метод : ${CYAN}$([ "$cf_method" == "1" ] && echo "Token" || echo "Login")${RESET}"
echo -e "  Uptime Kuma      : ${CYAN}$([ "$install_kuma" == "y" ] && echo "Да" || echo "Не")${RESET}"
echo -e "  WordPress сайтове: ${CYAN}$wp_count${RESET}"
echo ""
echo -e "${BOLD}  Файлове:${RESET}"
echo    "    📄 .env                (chmod 600)"
echo    "    📄 docker-compose.yml"
echo    "    📄 db-init/01-init.sql"
echo ""
echo -e "${BOLD}  Следваща стъпка:${RESET}"
echo -e "    ${GREEN}docker compose up -d${RESET}"
echo ""
warn "Запази .env файла на сигурно място — съдържа паролите!"
echo -e "${BOLD}════════════════════════════════════════════════════${RESET}\n"
