#!/bin/bash
# ==============================================================================
# School Management System - Linux Production Installer
# Pulls the pre-built image from our registry. No source, no build.
# ==============================================================================
set -e

INSTALL_DIR="/opt/school-system"
DEFAULT_PORT="18080"
PROJECT_NAME="school-system-production"
REGISTRY="registry.yaasabatech.ideasgh.com"
REGISTRY_USER="school-installer"
REGISTRY_PASS="ChangeThisToAStrongPassword"
IMAGE="$REGISTRY/school-system:latest"
COMPOSE_URL="https://sms.yaasabatech.ideasgh.com/downloads/docker-compose.yml"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

echo -e "${CYAN}${BOLD}====================================================${NC}"
echo -e "${CYAN}${BOLD}   School Management System - Production Installer${NC}"
echo -e "${CYAN}${BOLD}====================================================${NC}"

if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root (or with sudo).${NC}"
    exit 1
fi

# ==============================================================================
# [1/7] Docker
# ==============================================================================
echo -e "\n${YELLOW}[1/7] Checking Docker environment...${NC}"
if ! command -v docker >/dev/null 2>&1; then
    echo -e "${YELLOW}Docker not found. Installing...${NC}"
    curl -fsSL https://get.docker.com | sh
    systemctl enable --now docker
fi
if ! docker compose version >/dev/null 2>&1; then
    echo -e "${RED}Docker Compose v2 is not installed.${NC}"
    echo "Install docker-compose-plugin and re-run."
    exit 1
fi
echo -e "${GREEN}✓ Docker and Docker Compose found.${NC}"

# ==============================================================================
# [2/7] Prepare install directory
# ==============================================================================
echo -e "\n${YELLOW}[2/7] Preparing ${INSTALL_DIR}...${NC}"
cd /
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"
mkdir -p data backups

# ==============================================================================
# [3/7] Download compose file + create .env
# ==============================================================================
echo -e "\n${YELLOW}[3/7] Downloading configuration...${NC}"
curl -fsSL "$COMPOSE_URL" -o docker-compose.yml

if [ ! -f .env ]; then
    cat > .env <<EOF
SCHOOL_SYSTEM_PORT=$DEFAULT_PORT
JWT_SECRET=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | xxd -p -c 32)
EOF
fi

# ==============================================================================
# [4/7] Port selection
# ==============================================================================
echo -e "\n${YELLOW}[4/7] Validating port...${NC}"
TARGET_PORT=$(grep "^SCHOOL_SYSTEM_PORT=" .env | cut -d '=' -f2 | tr -d ' "\r\n')

is_port_occupied() {
    local port=$1
    if command -v ss >/dev/null 2>&1; then
        ss -tuln | grep -q ":${port} "
    elif command -v netstat >/dev/null 2>&1; then
        netstat -tuln | grep -q ":${port} "
    elif command -v lsof >/dev/null 2>&1; then
        lsof -i ":${port}" >/dev/null 2>&1
    else
        (echo >/dev/tcp/127.0.0.1/$port) 2>/dev/null
    fi
}

if is_port_occupied "$TARGET_PORT"; then
    ALT_PORT=$TARGET_PORT
    while is_port_occupied "$ALT_PORT"; do
        ALT_PORT=$((ALT_PORT + 1))
    done
    echo -e "${YELLOW}Port ${TARGET_PORT} busy, using ${ALT_PORT}${NC}"
    sed -i "s/^SCHOOL_SYSTEM_PORT=.*/SCHOOL_SYSTEM_PORT=$ALT_PORT/" .env
    TARGET_PORT=$ALT_PORT
fi
echo -e "${GREEN}✓ Host port: ${TARGET_PORT}${NC}"

# ==============================================================================
# [5/7] Registry login + pull
# ==============================================================================
echo -e "\n${YELLOW}[5/7] Authenticating with registry...${NC}"
echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin

echo -e "\n${YELLOW}[6/7] Pulling image and starting...${NC}"
docker compose -p "$PROJECT_NAME" down --remove-orphans 2>/dev/null || true
docker compose -p "$PROJECT_NAME" pull
docker compose -p "$PROJECT_NAME" up -d --force-recreate

# ==============================================================================
# [6/7] Management scripts
# ==============================================================================
echo -e "\n${YELLOW}[7/7] Creating management scripts...${NC}"

cat > "$INSTALL_DIR/start.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
docker compose -p $PROJECT_NAME up -d
echo "Started. Access: http://localhost:$TARGET_PORT"
EOF

cat > "$INSTALL_DIR/stop.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
docker compose -p $PROJECT_NAME down
echo "Stopped. Data preserved."
EOF

cat > "$INSTALL_DIR/restart.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
docker compose -p $PROJECT_NAME restart
echo "Restarted."
EOF

cat > "$INSTALL_DIR/update.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
echo "Logging into registry..."
echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
echo "Pulling latest image..."
docker compose -p $PROJECT_NAME pull
echo "Recreating container..."
docker compose -p $PROJECT_NAME up -d --force-recreate
echo "Done."
EOF

cat > "$INSTALL_DIR/backup.sh" <<'EOF'
#!/bin/bash
cd "$(dirname "$0")"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p backups
CONTAINER=$(docker compose -p school-system-production ps -q school-system)
if [ -z "$CONTAINER" ]; then
    echo "Container not running."
    exit 1
fi
docker exec "$CONTAINER" sh -c "mkdir -p /app/data/backups && cp /app/data/school.db /app/data/backups/backup-${TIMESTAMP}.db"
docker cp "$CONTAINER:/app/data/backups/backup-${TIMESTAMP}.db" "backups/school_${TIMESTAMP}.db"
echo "Backup saved: backups/school_${TIMESTAMP}.db"
EOF

cat > "$INSTALL_DIR/restore.sh" <<'EOF'
#!/bin/bash
cd "$(dirname "$0")"
[ -z "$1" ] && { echo "Usage: ./restore.sh <backup.db>"; exit 1; }
[ ! -f "$1" ] && { echo "Not found: $1"; exit 1; }
docker compose -p school-system-production down
docker run --rm \
  -v school-system-data:/app/data \
  -v "$(realpath "$1")":/backup.db \
  node:20-alpine sh -c "cp /backup.db /app/data/school.db && rm -f /app/data/school.db-wal /app/data/school.db-shm"
docker compose -p school-system-production up -d
echo "Restore complete."
EOF

cat > "$INSTALL_DIR/uninstall.sh" <<'EOF'
#!/bin/bash
read -rp "Backup before uninstall? [1=yes / 2=no / 3=cancel]: " c
cd "$(dirname "$0")"
case "$c" in
  1)
    mkdir -p backups
    C=$(docker compose -p school-system-production ps -q school-system 2>/dev/null || true)
    if [ -n "$C" ]; then
      docker exec "$C" sh -c "cp /app/data/school.db /app/data/pre-uninstall.db" 2>/dev/null || true
      docker cp "$C:/app/data/pre-uninstall.db" "backups/school_pre_uninstall_$(date +%Y%m%d_%H%M%S).db" 2>/dev/null || true
    fi
    docker compose -p school-system-production down --remove-orphans
    docker volume rm school-system-data 2>/dev/null || true
    find . -mindepth 1 -maxdepth 1 ! -name "backups" -exec rm -rf {} + 2>/dev/null || true
    ;;
  2)
    read -rp "Type DELETE: " x
    [ "$x" != "DELETE" ] && exit 0
    docker compose -p school-system-production down --remove-orphans
    docker volume rm school-system-data 2>/dev/null || true
    cd / && rm -rf "$(dirname "$0" | sed 's|^/||' | sed 's|^|/|')"
    ;;
  *) exit 0 ;;
esac
echo "Uninstall complete."
EOF

chmod +x "$INSTALL_DIR"/*.sh

# ==============================================================================
# Health check
# ==============================================================================
echo -e "\n${YELLOW}Verifying health...${NC}"
HEALTHY=false
for i in $(seq 1 30); do
    if curl -sf "http://localhost:${TARGET_PORT}/health" 2>/dev/null | grep -q '"status"'; then
        HEALTHY=true
        break
    fi
    sleep 1
done

echo ""
if [ "$HEALTHY" = true ]; then
    echo -e "${GREEN}${BOLD}✓ Installation Successful!${NC}"
else
    echo -e "${YELLOW}⚠ Container started but health check did not respond.${NC}"
    echo "Check: docker compose -p $PROJECT_NAME logs school-system --tail 50"
fi

echo ""
echo -e "Access:  ${CYAN}http://localhost:${TARGET_PORT}${NC}"
IP=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -n "$IP" ] && echo -e "Network: ${CYAN}http://${IP}:${TARGET_PORT}${NC}"
echo ""
