#!/bin/bash
# ============================================================
# Crypto Mining System — Management Script
# Usage: sudo bash manage.sh [start|stop|restart|status|logs|seed|backup]
# ============================================================
APP_DIR="/opt/crypto-mining"
DB_NAME="crypto_mining"

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"; }

case "${1:-help}" in

start)
    systemctl start cryptomining-api nginx mysql
    log "All services started"
    ;;

stop)
    systemctl stop cryptomining-api
    log "Backend stopped (Nginx + MySQL still running)"
    ;;

restart)
    systemctl restart cryptomining-api
    sleep 2
    systemctl is-active --quiet cryptomining-api && log "Restarted OK" || warn "Check logs!"
    ;;

status)
    echo ""
    echo -e "${BLUE}━━━ Service Status ━━━${NC}"
    systemctl status cryptomining-api --no-pager -l | head -20
    echo ""
    echo -e "${BLUE}━━━ Nginx Status ━━━${NC}"
    systemctl status nginx --no-pager | head -5
    echo ""
    echo -e "${BLUE}━━━ MySQL Status ━━━${NC}"
    systemctl status mysql --no-pager | head -5
    echo ""
    echo -e "${BLUE}━━━ Health Check ━━━${NC}"
    curl -s http://localhost:8000/health | python3 -m json.tool 2>/dev/null || echo "Backend not responding"
    ;;

logs)
    journalctl -u cryptomining-api -f --no-pager
    ;;

logs-nginx)
    tail -f /var/log/nginx/cryptomining_access.log /var/log/nginx/cryptomining_error.log
    ;;

seed)
    info "Seeding miners database from AI..."
    curl -s -X POST http://localhost:8000/seed/miners/sync | python3 -m json.tool
    ;;

seed-status)
    curl -s http://localhost:8000/seed/status | python3 -m json.tool
    ;;

backup)
    BACKUP_DIR="/opt/backups/cryptomining"
    mkdir -p ${BACKUP_DIR}
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    BACKUP_FILE="${BACKUP_DIR}/db_${TIMESTAMP}.sql.gz"

    source ${APP_DIR}/backend/.env 2>/dev/null || true
    mysqldump -u "${DB_USER:-cryptomining}" -p"${DB_PASSWORD:-}" \
        "${DB_NAME}" 2>/dev/null | gzip > "${BACKUP_FILE}"
    log "Database backup: ${BACKUP_FILE}"

    # Keep last 7 backups
    ls -t ${BACKUP_DIR}/db_*.sql.gz | tail -n +8 | xargs -r rm
    log "Old backups cleaned (keeping last 7)"
    ;;

update-env)
    nano ${APP_DIR}/backend/.env
    systemctl restart cryptomining-api
    log "Config updated and service restarted"
    ;;

miners-count)
    source ${APP_DIR}/backend/.env 2>/dev/null || true
    mysql -u "${DB_USER:-cryptomining}" -p"${DB_PASSWORD:-}" "${DB_NAME}" \
        -e "SELECT type, COUNT(*) as count FROM miners GROUP BY type; SELECT COUNT(*) as total FROM miners;" \
        2>/dev/null
    ;;

help|*)
    echo ""
    echo -e "${BLUE}Crypto Mining System — Management${NC}"
    echo ""
    echo "Usage: sudo bash manage.sh <command>"
    echo ""
    echo "Commands:"
    echo "  start       — Start all services"
    echo "  stop        — Stop backend"
    echo "  restart     — Restart backend"
    echo "  status      — Show service status + health check"
    echo "  logs        — Stream backend logs (Ctrl+C to exit)"
    echo "  logs-nginx  — Stream Nginx logs"
    echo "  seed        — Seed miners from AI (blocks until done)"
    echo "  seed-status — Check seeder status"
    echo "  backup      — Backup MySQL database"
    echo "  update-env  — Edit .env and restart"
    echo "  miners-count— Count miners by type"
    echo ""
    ;;
esac
