#!/bin/bash
# LXC Deployment Script for ChainID 138 Explorer Platform
# This script automates the deployment process

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$( cd "$SCRIPT_DIR/../.." && pwd )"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
CONTAINER_ID="${CONTAINER_ID:-100}"
CONTAINER_HOSTNAME="${CONTAINER_HOSTNAME:-explorer-prod}"
DOMAIN="${DOMAIN:-explorer.d-bis.org}"
SKIP_CONTAINER_CREATION="${SKIP_CONTAINER_CREATION:-false}"

echo -e "${GREEN}=== ChainID 138 Explorer Platform - LXC Deployment ===${NC}"
echo ""

# Check if running on Proxmox host
if ! command -v pct &> /dev/null; then
    echo -e "${RED}Error: This script must be run on a Proxmox host${NC}"
    exit 1
fi

# Phase 1: Create LXC Container
if [ "$SKIP_CONTAINER_CREATION" != "true" ]; then
    echo -e "${YELLOW}Phase 1: Creating LXC Container...${NC}"
    
    # Check if container already exists
    if pct list | grep -q "^$CONTAINER_ID "; then
        echo -e "${YELLOW}Container $CONTAINER_ID already exists. Skipping creation.${NC}"
        echo "Set SKIP_CONTAINER_CREATION=true to skip this check."
        read -p "Do you want to continue with existing container? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    else
        echo "Creating container $CONTAINER_ID..."
        pct create $CONTAINER_ID \
            local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst \
            --hostname $CONTAINER_HOSTNAME \
            --memory 16384 \
            --cores 4 \
            --swap 4096 \
            --storage local-lvm \
            --rootfs local-lvm:100 \
            --net0 name=eth0,bridge=vmbr0,ip=dhcp \
            --unprivileged 0 \
            --features nesting=1 \
            --start 1
        
        echo "Waiting for container to start..."
        sleep 5
    fi
fi

# Phase 2: Initial Container Setup
echo -e "${YELLOW}Phase 2: Initial Container Setup...${NC}"

cat << 'INITSCRIPT' | pct exec $CONTAINER_ID bash
set -e

# Update system
apt update && apt upgrade -y

# Install essential packages
apt install -y curl wget git vim net-tools ufw fail2ban \
    unattended-upgrades apt-transport-https ca-certificates \
    gnupg lsb-release software-properties-common

# Set timezone
timedatectl set-timezone UTC

# Create deployment user
if ! id "explorer" &>/dev/null; then
    adduser --disabled-password --gecos "" explorer
    usermod -aG sudo explorer
    echo "explorer ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
fi
INITSCRIPT

echo -e "${GREEN}✓ Container setup complete${NC}"

# Phase 3: Install Dependencies
echo -e "${YELLOW}Phase 3: Installing Dependencies...${NC}"

cat << 'DEPSCRIPT' | pct exec $CONTAINER_ID bash
set -e

# Install Go
if ! command -v go &> /dev/null; then
    cd /tmp
    wget -q https://go.dev/dl/go1.21.6.linux-amd64.tar.gz
    rm -rf /usr/local/go
    tar -C /usr/local -xzf go1.21.6.linux-amd64.tar.gz
    echo 'export PATH=$PATH:/usr/local/go/bin' >> /etc/profile
    export PATH=$PATH:/usr/local/go/bin
fi

# Install Node.js
if ! command -v node &> /dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt install -y nodejs
fi

# Install Docker
if ! command -v docker &> /dev/null; then
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    apt update
    apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    systemctl enable docker
    systemctl start docker
    usermod -aG docker explorer
fi

# Install PostgreSQL
if ! command -v psql &> /dev/null; then
    sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
    wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
    apt update
    apt install -y postgresql-16 postgresql-contrib-16
fi

# Install Nginx
if ! command -v nginx &> /dev/null; then
    apt install -y nginx
fi

# Install cloudflared
if ! command -v cloudflared &> /dev/null; then
    cd /tmp
    wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
    dpkg -i cloudflared-linux-amd64.deb || apt install -f -y
fi
DEPSCRIPT

echo -e "${GREEN}✓ Dependencies installed${NC}"

# Phase 4: Deploy Application
echo -e "${YELLOW}Phase 4: Deploying Application...${NC}"

# Copy project files to container (assuming git clone on host)
echo "Note: You'll need to clone the repository inside the container or copy files"
echo "For now, the script will prepare the structure"

cat << 'APPSCRIPT' | pct exec $CONTAINER_ID bash -s
set -e
mkdir -p /home/explorer/explorer-monorepo
chown explorer:explorer /home/explorer/explorer-monorepo
APPSCRIPT

echo -e "${YELLOW}Please complete the deployment manually:${NC}"
echo "1. Clone repository inside container: pct exec $CONTAINER_ID"
echo "2. Copy .env file and configure"
echo "3. Run migrations"
echo "4. Build applications"
echo "5. Configure services"
echo ""
echo "See DEPLOYMENT_GUIDE.md for complete instructions"

echo -e "${GREEN}=== Deployment Script Complete ===${NC}"

