#!/bin/bash
set -e

# Stop and remove any existing pod
/usr/bin/podman pod stop translynx-services 2>/dev/null || true
/usr/bin/podman pod rm -f translynx-services 2>/dev/null || true

# Create the pod
/usr/bin/podman pod create --name translynx-services   -p 5000:5000   -p 6379:6379   -p 8000:8000   -p 8001:8001   -p 9000:9000

# Start all services with restart policies
# LibreTranslate: Auto-download all languages on demand
/usr/bin/podman run -d --pull=never --name libretranslate --pod translynx-services   --restart=always   -v /home/local/translynx/libretranslate/models:/home/libretranslate/.local/share:Z   docker.io/libretranslate/libretranslate:latest --port 5000

/usr/bin/podman run -d --pull=never --name deepseek-proxy --pod translynx-services   --restart=always   localhost/deepseek-proxy:latest

/usr/bin/podman run -d --pull=never --name pdf-processor-ocr --pod translynx-services   --restart=always   localhost/pdf-processor-ocr:siliconflow

/usr/bin/podman run -d --pull=never --name translynx-backend --pod translynx-services   --restart=always   --env-file /home/local/translynx/backend/.env   localhost/translynx-backend:latest

# Wait for services to be up
sleep 5

# Add nftables rule to allow all traffic to podman network
# This ensures nginx can reach containers regardless of their assigned IP
if /usr/sbin/nft list chain ip filter CNI-FORWARD >/dev/null 2>&1; then
    # Check if subnet rule already exists
    if ! /usr/sbin/nft list chain ip filter CNI-FORWARD | grep -q '10.88.0.0/16 accept'; then
        /usr/sbin/nft insert rule ip filter CNI-FORWARD ip daddr 10.88.0.0/16 accept
        echo "Added nftables rule for podman subnet"
    fi
fi

echo "TransLynx services started successfully"
