#!/bin/bash
# ============================================================
# Crypto Mining System — Ubuntu Server Full Install Script
# Tested on Ubuntu 22.04 LTS / 24.04 LTS
# Run as root: sudo bash install.sh
# ============================================================
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; BOLD='\033[1m'; 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}[✗] ERROR:${NC} $1"; exit 1; }
step() { echo -e "\n${BOLD}${BLUE}━━━ $1 ━━━${NC}"; }

# ── Require root ─────────────────────────────────────────────
[[ $EUID -ne 0 ]] && err "Run as root: sudo bash install.sh"

# ── Config ───────────────────────────────────────────────────
APP_USER="cryptomining"
APP_DIR="/opt/crypto-mining"
DOMAIN="${DOMAIN:-_}"          # set via env: DOMAIN=example.com sudo bash install.sh
DB_NAME="crypto_mining"
DB_USER="cryptomining"
DB_PASS=$(openssl rand -base64 24 | tr -d '/+=')
PYTHON_VER="3.11"
NODE_VER="20"

echo ""
echo -e "${BOLD}${BLUE}╔══════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${BLUE}║  Crypto Mining Profitability System Setup    ║${NC}"
echo -e "${BOLD}${BLUE}║  Ubuntu Server Installer                     ║${NC}"
echo -e "${BOLD}${BLUE}╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  Domain:   ${YELLOW}${DOMAIN}${NC}"
echo -e "  App dir:  ${YELLOW}${APP_DIR}${NC}"
echo -e "  App user: ${YELLOW}${APP_USER}${NC}"
echo ""

# ══════════════════════════════════════════════════════════════
step "1 — System Update & Base Packages"
# ══════════════════════════════════════════════════════════════
apt-get update -qq
apt-get install -y -qq \
    curl wget git unzip gnupg ca-certificates \
    build-essential libssl-dev libffi-dev \
    software-properties-common apt-transport-https \
    ufw fail2ban logrotate
log "Base packages installed"

# ══════════════════════════════════════════════════════════════
step "2 — Python ${PYTHON_VER}"
# ══════════════════════════════════════════════════════════════
add-apt-repository -y ppa:deadsnakes/ppa &>/dev/null
apt-get update -qq
apt-get install -y -qq \
    python${PYTHON_VER} python${PYTHON_VER}-venv \
    python${PYTHON_VER}-dev python3-pip
update-alternatives --install /usr/bin/python3 python3 /usr/bin/python${PYTHON_VER} 1 || true
log "Python ${PYTHON_VER} installed"

# ══════════════════════════════════════════════════════════════
step "3 — Node.js ${NODE_VER}"
# ══════════════════════════════════════════════════════════════
curl -fsSL https://deb.nodesource.com/setup_${NODE_VER}.x | bash - &>/dev/null
apt-get install -y -qq nodejs
npm install -g pm2 &>/dev/null
log "Node.js $(node --version) + PM2 installed"

# ══════════════════════════════════════════════════════════════
step "4 — MySQL 8"
# ══════════════════════════════════════════════════════════════
apt-get install -y -qq mysql-server

# Secure MySQL and create DB/user
mysql -u root <<MYSQL_SETUP
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${DB_PASS}_root';
FLUSH PRIVILEGES;
CREATE DATABASE IF NOT EXISTS ${DB_NAME}
  CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SETUP

systemctl enable --now mysql
log "MySQL configured: db=${DB_NAME} user=${DB_USER}"

# ══════════════════════════════════════════════════════════════
step "5 — Nginx"
# ══════════════════════════════════════════════════════════════
apt-get install -y -qq nginx
systemctl enable nginx
log "Nginx installed"

# ══════════════════════════════════════════════════════════════
step "6 — App User & Directory"
# ══════════════════════════════════════════════════════════════
if ! id "$APP_USER" &>/dev/null; then
    useradd -r -m -s /bin/bash -d /home/${APP_USER} ${APP_USER}
    log "User ${APP_USER} created"
fi

mkdir -p ${APP_DIR}/{backend,frontend,logs}
chown -R ${APP_USER}:${APP_USER} ${APP_DIR}
log "App directory: ${APP_DIR}"

# ══════════════════════════════════════════════════════════════
step "7 — Copy Application Files"
# ══════════════════════════════════════════════════════════════
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"

cp -r "${PROJECT_ROOT}/backend/." "${APP_DIR}/backend/"
cp -r "${PROJECT_ROOT}/frontend/." "${APP_DIR}/frontend/"
cp -r "${PROJECT_ROOT}/database/." "${APP_DIR}/database/"
chown -R ${APP_USER}:${APP_USER} ${APP_DIR}
log "Application files copied"

# ══════════════════════════════════════════════════════════════
step "8 — Backend Python Environment"
# ══════════════════════════════════════════════════════════════
cd ${APP_DIR}/backend
sudo -u ${APP_USER} python${PYTHON_VER} -m venv venv
sudo -u ${APP_USER} venv/bin/pip install -q --upgrade pip
sudo -u ${APP_USER} venv/bin/pip install -q -r requirements.txt
log "Backend virtual environment ready"

# ══════════════════════════════════════════════════════════════
step "9 — Create .env"
# ══════════════════════════════════════════════════════════════
API_SECRET=$(openssl rand -hex 32)

cat > ${APP_DIR}/backend/.env <<ENV
# ── Database ──────────────────────
DB_HOST=localhost
DB_PORT=3306
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASS}
DB_NAME=${DB_NAME}

# ── OpenRouter AI ─────────────────
OPENROUTER_API_KEY=REPLACE_WITH_YOUR_KEY
OPENROUTER_MODEL=openai/gpt-4o-mini

# ── CoinGecko ─────────────────────
COINGECKO_API_KEY=

# ── Security ──────────────────────
API_SECRET_KEY=${API_SECRET}
RATE_LIMIT_PER_MINUTE=60

# ── App ───────────────────────────
APP_ENV=production
LOG_LEVEL=INFO
ENV

chown ${APP_USER}:${APP_USER} ${APP_DIR}/backend/.env
chmod 640 ${APP_DIR}/backend/.env
log ".env created (edit OPENROUTER_API_KEY before starting)"

# ══════════════════════════════════════════════════════════════
step "10 — Initialize Database Schema"
# ══════════════════════════════════════════════════════════════
mysql -u ${DB_USER} -p${DB_PASS} ${DB_NAME} < ${APP_DIR}/database/schema.sql
log "Database schema imported (with fallback miners)"

# ══════════════════════════════════════════════════════════════
step "11 — Build React Frontend"
# ══════════════════════════════════════════════════════════════
cd ${APP_DIR}/frontend

# Point frontend to backend API
cat > .env.production <<FENV
VITE_API_BASE_URL=/api
FENV

sudo -u ${APP_USER} npm install --silent
sudo -u ${APP_USER} npm run build
log "Frontend built → ${APP_DIR}/frontend/dist"

# ══════════════════════════════════════════════════════════════
step "12 — Systemd Service (Backend)"
# ══════════════════════════════════════════════════════════════
cat > /etc/systemd/system/cryptomining-api.service <<SERVICE
[Unit]
Description=Crypto Mining Profitability API (FastAPI)
After=network.target mysql.service
Wants=mysql.service

[Service]
Type=exec
User=${APP_USER}
Group=${APP_USER}
WorkingDirectory=${APP_DIR}/backend
ExecStart=${APP_DIR}/backend/venv/bin/uvicorn app.main:app \
    --host 127.0.0.1 \
    --port 8000 \
    --workers 2 \
    --log-level info \
    --access-log
ExecReload=/bin/kill -HUP \$MAINPID
Restart=always
RestartSec=5
KillMode=mixed
TimeoutStopSec=30

# Security hardening
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ReadWritePaths=${APP_DIR}/backend/logs
EnvironmentFile=${APP_DIR}/backend/.env

StandardOutput=journal
StandardError=journal
SyslogIdentifier=cryptomining-api

[Install]
WantedBy=multi-user.target
SERVICE

systemctl daemon-reload
systemctl enable cryptomining-api
log "Systemd service created: cryptomining-api"

# ══════════════════════════════════════════════════════════════
step "13 — Nginx Configuration"
# ══════════════════════════════════════════════════════════════
cat > /etc/nginx/sites-available/cryptomining <<NGINX
server {
    listen 80;
    listen [::]:80;
    server_name ${DOMAIN};

    root ${APP_DIR}/frontend/dist;
    index index.html;

    # Gzip
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # API → FastAPI backend
    location /api/ {
        proxy_pass http://127.0.0.1:8000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        proxy_read_timeout 60s;
        proxy_connect_timeout 10s;
        proxy_send_timeout 60s;
    }

    # React SPA — serve index.html for all routes
    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # Static assets — long cache
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # Block access to hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    access_log /var/log/nginx/cryptomining_access.log;
    error_log  /var/log/nginx/cryptomining_error.log;
}
NGINX

ln -sf /etc/nginx/sites-available/cryptomining /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl reload nginx
log "Nginx configured"

# ══════════════════════════════════════════════════════════════
step "14 — UFW Firewall"
# ══════════════════════════════════════════════════════════════
ufw --force reset &>/dev/null
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 'Nginx Full'
ufw --force enable
log "Firewall: SSH + HTTP/HTTPS allowed"

# ══════════════════════════════════════════════════════════════
step "15 — Logrotate"
# ══════════════════════════════════════════════════════════════
cat > /etc/logrotate.d/cryptomining <<LOGROTATE
${APP_DIR}/backend/logs/*.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    create 0640 ${APP_USER} ${APP_USER}
    postrotate
        systemctl reload cryptomining-api 2>/dev/null || true
    endscript
}
LOGROTATE
log "Log rotation configured"

# ══════════════════════════════════════════════════════════════
step "16 — Start Backend Service"
# ══════════════════════════════════════════════════════════════
systemctl start cryptomining-api
sleep 3
if systemctl is-active --quiet cryptomining-api; then
    log "Backend service is running"
else
    warn "Backend failed to start — check: journalctl -u cryptomining-api -n 50"
fi

# ══════════════════════════════════════════════════════════════
step "17 — Save Credentials"
# ══════════════════════════════════════════════════════════════
CREDS_FILE="/root/cryptomining_credentials.txt"
cat > ${CREDS_FILE} <<CREDS
============================================
 Crypto Mining System — Server Credentials
 Generated: $(date)
============================================

MySQL:
  Host:     localhost
  Database: ${DB_NAME}
  User:     ${DB_USER}
  Password: ${DB_PASS}

App:
  Directory: ${APP_DIR}
  User:      ${APP_USER}
  Env file:  ${APP_DIR}/backend/.env

API Secret Key: ${API_SECRET}

IMPORTANT:
  Edit OPENROUTER_API_KEY in:
  ${APP_DIR}/backend/.env
============================================
CREDS
chmod 600 ${CREDS_FILE}

# ══════════════════════════════════════════════════════════════
echo ""
echo -e "${GREEN}${BOLD}╔══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}${BOLD}║         Installation Complete! ✓             ║${NC}"
echo -e "${GREEN}${BOLD}╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  Frontend:    ${BLUE}http://$(curl -s ifconfig.me 2>/dev/null || echo 'YOUR_IP')${NC}"
echo -e "  API Docs:    ${BLUE}http://$(curl -s ifconfig.me 2>/dev/null || echo 'YOUR_IP')/api/docs${NC}"
echo -e "  Credentials: ${YELLOW}${CREDS_FILE}${NC}"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo -e "  1. Edit OPENROUTER_API_KEY:"
echo -e "     ${BLUE}nano ${APP_DIR}/backend/.env${NC}"
echo -e "  2. Restart backend:"
echo -e "     ${BLUE}sudo systemctl restart cryptomining-api${NC}"
echo -e "  3. Seed miners database:"
echo -e "     ${BLUE}curl -X POST http://localhost:8000/seed/miners/sync${NC}"
echo -e "  4. (Optional) Setup SSL:"
echo -e "     ${BLUE}sudo bash $(dirname $0)/setup_ssl.sh your-domain.com${NC}"
echo ""
