#!/bin/bash
# Simple script to setup basic Incus instances for Veza
# Usage: ./setup-basic-incus.sh

set -euo pipefail

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

NETWORK="veza-network"
PROFILE="veza-profile"

echo -e "${BLUE}🚀 Setting up basic Incus infrastructure for Veza${NC}"
echo ""

# Check if incus is installed
if ! command -v incus >/dev/null 2>&1; then
    echo -e "${RED}❌ ERROR: incus is not installed${NC}"
    echo "   Install with: sudo snap install incus"
    exit 1
fi

# Check host NAT tooling (Incus needs nftables or iptables to implement ipv4.nat=true)
echo -e "${BLUE}0. Checking host NAT tooling (nftables/iptables)...${NC}"
if ! command -v nft >/dev/null 2>&1 && ! command -v iptables >/dev/null 2>&1; then
    echo -e "${RED}❌ ERROR: Neither 'nft' nor 'iptables' is available on the host.${NC}"
    echo "   Incus NAT (ipv4.nat=true) cannot work without one of them."
    echo ""
    echo "   Fedora:"
    echo "     sudo dnf install -y nftables iptables-nft"
    echo ""
    echo "   Debian/Ubuntu:"
    echo "     sudo apt-get update && sudo apt-get install -y nftables iptables"
    exit 1
fi
echo -e "${GREEN}   ✅ Host NAT tooling present${NC}"

# 0. Ensure IP forwarding is enabled (required for NAT)
echo -e "${BLUE}0. Checking IP forwarding (required for NAT)...${NC}"
if [ "$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo 0)" != "1" ]; then
    echo -e "${YELLOW}   IP forwarding is disabled, enabling...${NC}"
    if echo "1" | sudo tee /proc/sys/net/ipv4/ip_forward >/dev/null 2>&1; then
        echo -e "${GREEN}   ✅ IP forwarding enabled${NC}"
        # Make it persistent
        if ! grep -q "net.ipv4.ip_forward=1" /etc/sysctl.conf 2>/dev/null; then
            echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf >/dev/null
            echo -e "${GREEN}   ✅ IP forwarding made persistent${NC}"
        fi
    else
        echo -e "${RED}   ❌ Failed to enable IP forwarding${NC}"
        echo "   Run as root: echo 1 > /proc/sys/net/ipv4/ip_forward"
        exit 1
    fi
else
    echo -e "${GREEN}   ✅ IP forwarding is enabled${NC}"
fi

# 1. Create network
echo -e "${BLUE}1. Creating network ${NETWORK}...${NC}"
if incus network show ${NETWORK} >/dev/null 2>&1; then
    echo -e "${YELLOW}   Network ${NETWORK} already exists${NC}"
    # Ensure NAT is enabled
    incus network set ${NETWORK} ipv4.nat=true 2>/dev/null || true
else
    incus network create ${NETWORK} \
        ipv4.address=10.10.10.1/24 \
        ipv4.nat=true \
        ipv4.dhcp=true \
        dns.mode=managed \
        dns.nameservers=8.8.8.8,1.1.1.1
    echo -e "${GREEN}   ✅ Network ${NETWORK} created${NC}"
fi

# 2. Create profile
echo -e "${BLUE}2. Creating profile ${PROFILE}...${NC}"
if incus profile show ${PROFILE} >/dev/null 2>&1; then
    echo -e "${YELLOW}   Profile ${PROFILE} already exists${NC}"
else
    incus profile create ${PROFILE}
    echo -e "${GREEN}   ✅ Profile ${PROFILE} created${NC}"
fi

# 3. Add root device to profile
echo -e "${BLUE}3. Configuring profile devices...${NC}"
if incus profile show ${PROFILE} | grep -q "root:"; then
    echo -e "${YELLOW}   Root device already configured${NC}"
else
    incus profile device add ${PROFILE} root disk path=/ pool=default 2>/dev/null || \
        incus profile device add ${PROFILE} root disk path=/ 2>/dev/null || {
        echo -e "${RED}   ❌ Failed to add root device${NC}"
        exit 1
    }
    echo -e "${GREEN}   ✅ Root device added${NC}"
fi

# 4. Add network device to profile
if incus profile show ${PROFILE} | grep -q "eth0:"; then
    echo -e "${YELLOW}   Network device already configured${NC}"
else
    incus profile device add ${PROFILE} eth0 nic network=${NETWORK} 2>/dev/null || {
        echo -e "${RED}   ❌ Failed to add network device${NC}"
        exit 1
    }
    echo -e "${GREEN}   ✅ Network device added${NC}"
fi

# 5. Verify network configuration
echo -e "${BLUE}4. Verifying network configuration...${NC}"
NETWORK_CONFIG=$(incus network show ${NETWORK})
if echo "${NETWORK_CONFIG}" | grep -q "ipv4.nat: \"true\"" && \
   echo "${NETWORK_CONFIG}" | grep -q "ipv4.dhcp: \"true\""; then
    echo -e "${GREEN}   ✅ Network properly configured (NAT and DHCP enabled)${NC}"
else
    echo -e "${YELLOW}   ⚠️  Updating network configuration...${NC}"
    incus network set ${NETWORK} ipv4.dhcp=true 2>/dev/null || true
    incus network set ${NETWORK} dns.mode=managed 2>/dev/null || true
    incus network set ${NETWORK} dns.nameservers=8.8.8.8,1.1.1.1 2>/dev/null || true
    echo -e "${GREEN}   ✅ Network configuration updated${NC}"
fi

# 6. Verify profile configuration
echo -e "${BLUE}5. Verifying profile configuration...${NC}"
PROFILE_CONFIG=$(incus profile show ${PROFILE})
if echo "${PROFILE_CONFIG}" | grep -q "root:" && \
   echo "${PROFILE_CONFIG}" | grep -q "eth0:"; then
    echo -e "${GREEN}   ✅ Profile properly configured (root and network devices)${NC}"
else
    echo -e "${RED}   ❌ Profile configuration incomplete${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}✅ Basic Incus infrastructure setup complete!${NC}"
echo ""
echo "Network: ${NETWORK}"
echo "Profile: ${PROFILE}"
echo ""
echo "You can now deploy services with:"
echo "  ./deploy-service-native.sh <service-name>"
echo ""
echo "Available services: infra, backend-api, chat-server, stream-server, web, haproxy"
