#!/usr/bin/env bash
# deploy-local.sh - Local deployment script for stability-agent
# This script is intended to be run on the target node.

set -e

# Node resolution: positional argument takes precedence over NODE_NAME env
NODE_NAME=${1:-$NODE_NAME}

if [[ -z "$NODE_NAME" ]]; then
    echo "Usage: $0 <node-name>"
    echo "Example: $0 piha"
    exit 1
fi

# Validation
case "$NODE_NAME" in
    piha|chelsty|solaria|vps)
        ;;
    *)
        echo "Error: Invalid node '$NODE_NAME'. Must be one of: piha, chelsty, solaria, vps"
        exit 1
        ;;
esac

# Default values
REDIS_HOST=${REDIS_HOST:-100.108.208.3}
REDIS_PORT=${REDIS_PORT:-6379}
REDIS_ENABLED=${REDIS_ENABLED:-true}

echo "--- Deploying stability-agent on $NODE_NAME ---"

# Check for docker-compose or docker compose
if docker compose version >/dev/null 2>&1; then
    DOCKER_COMPOSE="docker compose"
else
    DOCKER_COMPOSE="docker-compose"
fi

# Use host-specific override if it exists
OVERRIDE_FILE="../../hosts/$NODE_NAME/runtime/stability-agent/docker-compose.override.yml"
COMPOSE_ARGS="-f docker-compose.yml"

if [ -f "$OVERRIDE_FILE" ]; then
    echo "Using override file: $OVERRIDE_FILE"
    COMPOSE_ARGS="$COMPOSE_ARGS -f $OVERRIDE_FILE"
fi

# Run deployment
NODE_NAME=$NODE_NAME \
REDIS_HOST=$REDIS_HOST \
REDIS_PORT=$REDIS_PORT \
REDIS_ENABLED=$REDIS_ENABLED \
$DOCKER_COMPOSE $COMPOSE_ARGS up -d --build --force-recreate

echo "Deployment finished."
