#!/bin/bash
# Deploy a Veza service to Incus
# Usage: ./deploy-service.sh <service-name>

set -e

SERVICE=$1
PROJECT_NAME="veza"
NETWORK="veza-network"
PROFILE="veza-profile"

if [ -z "$SERVICE" ]; then
    echo "Usage: $0 <service-name>"
    echo "Services: backend-api, chat-server, stream-server, web, haproxy"
    exit 1
fi

CONTAINER_NAME="${PROJECT_NAME}-${SERVICE}"

echo "📦 Deploying ${SERVICE} to Incus..."

# Check if network exists
if ! incus network show ${NETWORK} >/dev/null 2>&1; then
    echo "Creating network ${NETWORK}..."
    incus network create ${NETWORK} \
        ipv4.address=10.10.10.1/24 \
        ipv4.nat=true
fi

# Check if profile exists
if ! incus profile show ${PROFILE} >/dev/null 2>&1; then
    echo "Creating profile ${PROFILE}..."
    incus profile create ${PROFILE}
    incus profile device add ${PROFILE} eth0 nic network=${NETWORK}
fi

# Delete existing container if it exists
if incus list -c n --format csv | grep -q "^${CONTAINER_NAME}$"; then
    echo "Removing existing container ${CONTAINER_NAME}..."
    incus delete ${CONTAINER_NAME} --force
fi

# Create and start container
echo "Creating container ${CONTAINER_NAME}..."
incus init images:debian/13 ${CONTAINER_NAME} --profile ${PROFILE}

# Install Docker in container
echo "Installing Docker in container..."
incus exec ${CONTAINER_NAME} -- bash -c "
    apt-get update
    apt-get install -y docker.io docker-compose
    systemctl enable docker
    systemctl start docker
"

# Copy service files
echo "Copying service files..."
case ${SERVICE} in
    backend-api)
        incus file push -r ../../veza-backend-api ${CONTAINER_NAME}/opt/veza/
        ;;
    chat-server)
        incus file push -r ../../veza-chat-server ${CONTAINER_NAME}/opt/veza/
        ;;
    stream-server)
        incus file push -r ../../veza-stream-server ${CONTAINER_NAME}/opt/veza/
        ;;
    web)
        incus file push -r ../../apps/web ${CONTAINER_NAME}/opt/veza/
        ;;
    haproxy)
        incus file push ../../config/haproxy/haproxy.cfg ${CONTAINER_NAME}/etc/haproxy/
        ;;
esac

# Start container
echo "Starting container..."
incus start ${CONTAINER_NAME}

echo "✅ ${SERVICE} deployed successfully!"
echo "Container: ${CONTAINER_NAME}"
echo "Access: incus exec ${CONTAINER_NAME} -- bash"
