#!/usr/bin/env bash
set -e

echo "=========================================================="
echo "  Deploying Platform via Podman 5.x on cPanel Server"
echo "=========================================================="

# 1. Ensure user containers.conf exists to handle single-mapping rootless mode
mkdir -p ~/.config/containers
CONTAINERS_CONF_FILE="$HOME/.config/containers/containers.conf"
if [ ! -f "$CONTAINERS_CONF_FILE" ] || ! grep -q "default_sysctls" "$CONTAINERS_CONF_FILE"; then
    echo "[+] Configuring ~/.config/containers/containers.conf for rootless compatibility..."
    cat <<EOF > "$CONTAINERS_CONF_FILE"
[containers]
cgroup_manager = "cgroupfs"
default_sysctls = []

[engine]
cgroup_manager = "cgroupfs"
events_logger = "file"
EOF
fi

# 2. Check Podman availability
if ! command -v podman &> /dev/null; then
    echo "Error: podman command not found!"
    exit 1
fi

PODMAN_VER=$(podman -v)
echo "[+] Detected $PODMAN_VER"

# 3. Run Podman system migrate for user namespace compatibility
echo "[+] Running podman system migrate for user namespace compatibility..."
podman system migrate || true

# 4. Clean up any stale/failed containers
echo "[+] Removing any stale container instances..."
podman rm -f domain_platform_db domain_platform_backend domain_platform_frontend 2>/dev/null || true

# 5. Check for .env file
if [ ! -f .env ]; then
    echo "[+] Creating .env file from template..."
    cat <<EOF > .env
DB_USER=domainuser
DB_PASSWORD=$(openssl rand -hex 12)
DB_NAME=domainplatform
SECRET_KEY=$(openssl rand -hex 32)
VITE_API_URL=http://localhost:8000
EOF
    echo "[+] Created .env file with generated credentials."
fi

# 6. Determine Compose tool
if podman compose version &> /dev/null; then
    COMPOSE_CMD="podman compose"
elif command -v podman-compose &> /dev/null; then
    COMPOSE_CMD="podman-compose"
else
    echo "[-] Installing podman-compose via python pip..."
    pip3 install --user podman-compose || python3 -m pip install --user podman-compose
    COMPOSE_CMD="podman-compose"
fi

echo "[+] Using compose engine: $COMPOSE_CMD"

# 7. Build and start containers
echo "[+] Building and starting containers in detached mode..."
$COMPOSE_CMD up -d --build

echo ""
echo "=========================================================="
echo "  Platform Deployed Successfully via Podman!"
echo "=========================================================="
echo "  Frontend URL: http://localhost:3000"
echo "  Backend API:  http://localhost:8000"
echo "=========================================================="
echo "  View status:  podman ps"
echo "  View logs:    $COMPOSE_CMD logs -f"
echo "=========================================================="
