#!/bin/sh
# MCP-ZERO offline first resilience script
# Implements single connection attempt pattern

LOCK_FILE_PATH="/app/locks/offline.lock"
CONFIG_FILE="/app/config/offline.json"

# Check if offline lock file exists
if [ -f "${LOCK_FILE_PATH}" ]; then
  echo "Offline lock file detected, starting in permanent offline mode"
  export MCP_OFFLINE_MODE=true
  exit 0
fi

# Check if offline mode is configured
if [ -f "${CONFIG_FILE}" ]; then
  OFFLINE_CONFIGURED=$(grep -o '"enabled": true' "${CONFIG_FILE}" | wc -l)
  if [ "${OFFLINE_CONFIGURED}" -gt 0 ]; then
    echo "Offline mode configured in settings, starting in offline mode"
    export MCP_OFFLINE_MODE=true
    exit 0
  fi
fi

# Try to connect to monitoring endpoint
if [ -n "${MCP_MONITORING_ENDPOINT}" ]; then
  echo "Attempting connection to monitoring endpoint..."
  
  # Single connection attempt pattern
  if ! wget -q --spider --timeout=5 "${MCP_MONITORING_ENDPOINT}/health" 2>/dev/null; then
    echo "Connection failed, creating offline lock file and switching to offline mode"
    
    # Create offline lock file with timestamp
    echo "{\"created_at\": \"$(date -Iseconds)\", \"reason\": \"Connection attempt failed\", \"immutable\": true}" > "${LOCK_FILE_PATH}"
    chmod 444 "${LOCK_FILE_PATH}"
    
    export MCP_OFFLINE_MODE=true
  else
    echo "Connection successful, starting in online mode"
    export MCP_OFFLINE_MODE=false
  fi
fi

exit 0
