#!/bin/bash
# Access Omada Cloud Controller and check firewall rules for Blockscout
# This script helps automate access to the cloud controller web interface

set -euo pipefail

# Load environment variables
ENV_FILE="${HOME}/.env"
if [ ! -f "$ENV_FILE" ]; then
  echo "Error: .env file not found at $ENV_FILE"
  exit 1
fi

# Load environment variables manually to avoid issues with special characters
while IFS='=' read -r key value || [ -n "$key" ]; do
  # Skip comments and empty lines
  [[ "$key" =~ ^[[:space:]]*# ]] && continue
  [[ -z "$key" ]] && continue
  
  # Remove quotes if present
  value=$(echo "$value" | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")
  
  # Export variable
  export "$key=$value"
done < <(grep -v '^#' "$ENV_FILE" | grep -v '^$' | grep -iE "OMADA|TP_LINK|TPLINK")

# Omada Cloud Controller URL
CLOUD_CONTROLLER_URL="https://omada.tplinkcloud.com"

# Try to detect cloud controller credentials
# Common variable names for TP-Link/Omada cloud credentials
TP_LINK_USERNAME="${TP_LINK_USERNAME:-${OMADA_CLOUD_USERNAME:-${OMADA_TP_LINK_ID:-}}}"
TP_LINK_PASSWORD="${TP_LINK_PASSWORD:-${OMADA_CLOUD_PASSWORD:-${OMADA_TP_LINK_PASSWORD:-}}}"

# Fallback to admin credentials if cloud-specific ones aren't found
if [ -z "$TP_LINK_USERNAME" ]; then
  TP_LINK_USERNAME="${OMADA_ADMIN_USERNAME:-${OMADA_API_KEY:-}}"
fi

if [ -z "$TP_LINK_PASSWORD" ]; then
  TP_LINK_PASSWORD="${OMADA_ADMIN_PASSWORD:-${OMADA_API_SECRET:-}}"
fi

echo "════════════════════════════════════════"
echo "Omada Cloud Controller Access Helper"
echo "════════════════════════════════════════"
echo ""
echo "Cloud Controller URL: $CLOUD_CONTROLLER_URL"
echo ""

if [ -z "$TP_LINK_USERNAME" ] || [ -z "$TP_LINK_PASSWORD" ]; then
  echo "❌ Error: Cloud Controller credentials not found in .env file"
  echo ""
  echo "Required environment variables (one of these combinations):"
  echo "  Option 1 (TP-Link ID):"
  echo "    TP_LINK_USERNAME=your-tp-link-id"
  echo "    TP_LINK_PASSWORD=your-tp-link-password"
  echo ""
  echo "  Option 2 (Omada Cloud):"
  echo "    OMADA_CLOUD_USERNAME=your-cloud-username"
  echo "    OMADA_CLOUD_PASSWORD=your-cloud-password"
  echo ""
  echo "  Option 3 (Omada TP-Link ID):"
  echo "    OMADA_TP_LINK_ID=your-tp-link-id"
  echo "    OMADA_TP_LINK_PASSWORD=your-tp-link-password"
  echo ""
  echo "Available Omada-related variables in .env:"
  cat .env | grep -i "OMADA\|TP" | grep -v "^#" | sed 's/=.*/=<hidden>/' || echo "  (none found)"
  exit 1
fi

echo "✓ Credentials found in .env file"
echo ""
echo "To access Omada Cloud Controller:"
echo ""
echo "1. Open browser and navigate to:"
echo "   $CLOUD_CONTROLLER_URL"
echo ""
echo "2. Login with credentials:"
echo "   Username: $TP_LINK_USERNAME"
echo "   Password: [hidden - check .env file]"
echo ""
echo "3. After logging in:"
echo "   - Click 'Launch' on your Omada Controller"
echo "   - Navigate to: Settings → Firewall → Firewall Rules"
echo ""
echo "4. Check for firewall rules blocking Blockscout:"
echo "   - Destination IP: 192.168.11.140"
echo "   - Destination Port: 80"
echo "   - Action: Deny or Reject"
echo ""
echo "5. Create allow rule if needed:"
echo "   Name: Allow Internal to Blockscout HTTP"
echo "   Enable: Yes"
echo "   Action: Allow"
echo "   Direction: Forward"
echo "   Protocol: TCP"
echo "   Source IP: 192.168.11.0/24"
echo "   Destination IP: 192.168.11.140"
echo "   Destination Port: 80"
echo "   Priority: High (above deny rules)"
echo ""

# Check if we're in a graphical environment and can open browser
if command -v xdg-open &> /dev/null; then
  read -p "Open Omada Cloud Controller in browser? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Opening $CLOUD_CONTROLLER_URL..."
    xdg-open "$CLOUD_CONTROLLER_URL" 2>/dev/null || echo "Could not open browser automatically. Please open manually."
  fi
elif [ -n "$DISPLAY" ] && command -v open &> /dev/null; then
  read -p "Open Omada Cloud Controller in browser? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Opening $CLOUD_CONTROLLER_URL..."
    open "$CLOUD_CONTROLLER_URL" 2>/dev/null || echo "Could not open browser automatically. Please open manually."
  fi
else
  echo "Note: No graphical environment detected. Please open browser manually."
fi

echo ""
echo "════════════════════════════════════════"
echo "For detailed instructions, see:"
echo "  docs/OMADA_CLOUD_CONTROLLER_FIREWALL_GUIDE.md"
echo "════════════════════════════════════════"

