#!/usr/bin/env bash
LOG_FILE="/var/log/public_ip_monitor.log"
LAST_IP_FILE="/var/log/last_ip.txt"
MAKE_DIR="/root/hurricane/cloudflare/zones"  # CHANGE THIS to your Makefile directory

# Make sure log files exist
touch "$LOG_FILE"
touch "$LAST_IP_FILE"

while true; do
  TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
  echo "============================================" | tee -a "$LOG_FILE"
  echo "[$TIMESTAMP] Checking public IP..." | tee -a "$LOG_FILE"

  IP=""
  METHOD=""

  # Try api.ipify.org
  echo "[$TIMESTAMP] Trying api.ipify.org..." | tee -a "$LOG_FILE"
  IP=$(curl -s --max-time 10 https://api.ipify.org)

  if [[ -n "$IP" ]]; then
    METHOD="api.ipify.org"
    echo "[$TIMESTAMP] SUCCESS: Retrieved IP: $IP" | tee -a "$LOG_FILE"
  else
    echo "[$TIMESTAMP] FAILED: api.ipify.org did not return an IP." | tee -a "$LOG_FILE"

    echo "[$TIMESTAMP] Trying ifconfig.me..." | tee -a "$LOG_FILE"
    IP=$(curl -s --max-time 10 http://ifconfig.io)

    if [[ -n "$IP" ]]; then
      METHOD="ifconfig.me"
      echo "[$TIMESTAMP] SUCCESS: Retrieved IP: $IP" | tee -a "$LOG_FILE"
    else
      echo "[$TIMESTAMP] FAILED: ifconfig.me did not return an IP." | tee -a "$LOG_FILE"

      echo "[$TIMESTAMP] Trying dig opendns..." | tee -a "$LOG_FILE"
      IP=$(dig +short myip.opendns.com @resolver1.opendns.com)

      if [[ -n "$IP" ]]; then
        METHOD="dig opendns"
        echo "[$TIMESTAMP] SUCCESS: Retrieved IP: $IP" | tee -a "$LOG_FILE"
      else
        IP="FAILED TO RESOLVE"
        METHOD="All methods failed"
        echo "[$TIMESTAMP] ERROR: All methods failed to retrieve IP." | tee -a "$LOG_FILE"
      fi
    fi
  fi

  if [[ "$IP" == "FAILED TO RESOLVE" ]]; then
    echo "[$TIMESTAMP] ERROR: Could not determine public IP." | tee -a "$LOG_FILE"
  else
    # Read previous IP
    LAST_IP=$(cat "$LAST_IP_FILE")

    if [[ "$IP" != "$LAST_IP" ]]; then
      echo "[$TIMESTAMP] Detected IP change: $LAST_IP --> $IP" | tee -a "$LOG_FILE"

      echo "[$TIMESTAMP] Running 'make apply' in $MAKE_DIR..." | tee -a "$LOG_FILE"
      cd "$MAKE_DIR"
      make apply >> "$LOG_FILE" 2>&1

      echo "$IP" > "$LAST_IP_FILE"
      echo "[$TIMESTAMP] 'make apply' completed." | tee -a "$LOG_FILE"
    else
      echo "[$TIMESTAMP] No change detected. No action taken." | tee -a "$LOG_FILE"
    fi
  fi

  echo "[$TIMESTAMP] Sleeping 5 minutes..." | tee -a "$LOG_FILE"
  sleep 300
done


