#!/bin/bash
#
# LXC Docker Container Creation Script
#
# Creates a new LXC container with Docker pre-installed and configured
# for running containerized services.
#
# Usage: ./lxc-docker-create.sh <VMID> <HOSTNAME> <IP> <DISK_SIZE> <MEMORY> <CORES> [PROXMOX_HOST]
#
# Example: ./lxc-docker-create.sh 214 docker-pittsburgh-lxc 10.10.0.214 128G 16384 4
# Example with remote host: ./lxc-docker-create.sh 214 docker-pittsburgh-lxc 10.10.0.214 128G 16384 4 root@10.10.0.11
#
# Arguments:
#   VMID         - Proxmox container ID (e.g., 214)
#   HOSTNAME     - Container hostname (e.g., docker-pittsburgh-lxc)
#   IP           - Static IP address without CIDR (e.g., 10.10.0.214)
#   DISK_SIZE    - Root filesystem size (e.g., 128G)
#   MEMORY       - RAM in MB (e.g., 16384)
#   CORES        - CPU cores (e.g., 4)
#   PROXMOX_HOST - Optional SSH host for remote Proxmox (e.g., root@10.10.0.11)
#
# What this script does:
# 1. Creates LXC container with specified resources
# 2. Configures AppArmor for Docker compatibility
# 3. Enables nesting and keyctl features
# 4. Installs Docker and docker-compose-plugin
# 5. Sets up container to start on boot
#
# Prerequisites:
# - Ubuntu 20.04 template downloaded on Proxmox host
# - Sufficient storage on local-lvm
# - Network bridge vmbr0 configured
# - Gateway at 10.10.0.1
#

set -euo pipefail

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

# Function to print colored messages
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to execute commands on Proxmox host
execute_on_proxmox() {
    if [[ -n "${PROXMOX_HOST:-}" ]]; then
        ssh "$PROXMOX_HOST" "$@"
    else
        bash -c "$@"
    fi
}

# Parse arguments
if [[ $# -lt 6 ]]; then
    log_error "Insufficient arguments"
    echo "Usage: $0 <VMID> <HOSTNAME> <IP> <DISK_SIZE> <MEMORY> <CORES> [PROXMOX_HOST]"
    echo ""
    echo "Example: $0 214 docker-pittsburgh-lxc 10.10.0.214 128G 16384 4"
    echo "Example: $0 214 docker-pittsburgh-lxc 10.10.0.214 128G 16384 4 root@10.10.0.11"
    exit 1
fi

VMID=$1
HOSTNAME=$2
IP=$3
DISK_SIZE=$4
MEMORY=$5
CORES=$6
PROXMOX_HOST=${7:-}

# Configuration
TEMPLATE="local:vztmpl/ubuntu-20.04-standard_20.04-1_amd64.tar.gz"
GATEWAY="10.10.0.1"
NAMESERVER="8.8.8.8"
CIDR="24"

log_info "Starting LXC container creation"
log_info "Configuration:"
echo "  VMID:       $VMID"
echo "  Hostname:   $HOSTNAME"
echo "  IP:         $IP/$CIDR"
echo "  Disk:       $DISK_SIZE"
echo "  Memory:     $MEMORY MB"
echo "  Cores:      $CORES"
[[ -n "${PROXMOX_HOST:-}" ]] && echo "  Proxmox:    $PROXMOX_HOST" || echo "  Proxmox:    local"
echo ""

# Check if container already exists
log_info "Checking if container $VMID already exists..."
if execute_on_proxmox "pct status $VMID 2>/dev/null"; then
    log_error "Container $VMID already exists!"
    read -p "Do you want to destroy and recreate it? (yes/no): " -r
    if [[ $REPLY == "yes" ]]; then
        log_warn "Stopping and destroying container $VMID..."
        execute_on_proxmox "pct stop $VMID 2>/dev/null || true"
        execute_on_proxmox "pct destroy $VMID"
        log_info "Container $VMID destroyed"
    else
        log_error "Aborted by user"
        exit 1
    fi
fi

# Create the LXC container
log_info "Creating LXC container $VMID..."
execute_on_proxmox "pct create $VMID $TEMPLATE \
    --hostname $HOSTNAME \
    --memory $MEMORY \
    --cores $CORES \
    --rootfs local-lvm:$DISK_SIZE \
    --net0 name=eth0,bridge=vmbr0,ip=$IP/$CIDR,gw=$GATEWAY \
    --unprivileged 0 \
    --onboot 1 \
    --nameserver $NAMESERVER"

log_info "✅ Container created"

# Configure AppArmor and features
log_info "Configuring AppArmor profile and container features..."
execute_on_proxmox "cat >> /etc/pve/lxc/$VMID.conf << 'EOF'
lxc.apparmor.profile: unconfined
lxc.cgroup2.devices.allow: a
lxc.cap.drop:
EOF"

# Update features line
execute_on_proxmox "sed -i 's/^features:.*/features: nesting=1,keyctl=1/' /etc/pve/lxc/$VMID.conf"

log_info "✅ AppArmor and features configured"

# Start the container
log_info "Starting container $VMID..."
execute_on_proxmox "pct start $VMID"

log_info "Waiting 10 seconds for container to boot..."
sleep 10

# Install Docker
log_info "Installing Docker and dependencies..."
execute_on_proxmox "pct exec $VMID -- bash <<'DOCKER_INSTALL'
set -e

# Update package list
apt-get update

# Install prerequisites
apt-get install -y \
    ca-certificates \
    curl \
    gnupg \
    lsb-release

# Download and run Docker installation script
curl -fsSL https://get.docker.com -o /tmp/get-docker.sh
sh /tmp/get-docker.sh

# Install docker-compose-plugin
apt-get install -y docker-compose-plugin

# Enable Docker service
systemctl enable docker
systemctl start docker

# Verify installation
docker --version
docker compose version

echo '✅ Docker installation complete'
DOCKER_INSTALL"

log_info "✅ Docker installed successfully"

# Display completion message
echo ""
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info "🎉 LXC Container $VMID Ready!"
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Container Details:"
echo "  ID:       $VMID"
echo "  Hostname: $HOSTNAME"
echo "  IP:       $IP"
echo "  Status:   Running"
echo ""
echo "Next Steps:"
echo "  1. Copy SSH key (if needed):"
if [[ -n "${PROXMOX_HOST:-}" ]]; then
    echo "     ssh $PROXMOX_HOST \"cat ~/.ssh/id_rsa.pub | pct exec $VMID -- tee /root/.ssh/authorized_keys\""
else
    echo "     cat ~/.ssh/id_rsa.pub | pct exec $VMID -- tee /root/.ssh/authorized_keys"
fi
echo ""
echo "  2. Migrate data from source VM"
echo ""
echo "  3. Fix AppArmor in docker-compose files:"
echo "     ./fix-docker-apparmor.sh $IP"
echo ""
echo "  4. Start containers:"
echo "     ssh root@$IP 'cd /home/cal/container-data/[service] && docker compose up -d'"
echo ""
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
