#!/bin/bash

echo "[$(date)] --- DDNS Check Started ---"

# 1. Validate variables are not empty
if [ -z "$CF_API_TOKEN" ] || [ -z "$CF_ZONE_ID" ] || [ -z "$CF_RECORD_NAME" ]; then
    echo "ERROR: One or more environment variables (TOKEN, ZONE_ID, RECORD_NAME) are missing!"
    exit 1
fi

# 2. Get current public IP (Trying two services for reliability)
NEW_IP=$(curl -s https://api.ipify.org || curl -s https://ifconfig.me/ip)

if [[ ! $NEW_IP =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
    echo "ERROR: Could not get a valid Public IP."
    exit 1
fi

# 3. Get the current Record info from Cloudflare
RECORD_DATA=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/dns_records?name=$CF_RECORD_NAME&type=A" \
     -H "Authorization: Bearer $CF_API_TOKEN" \
     -H "Content-Type: application/json")

# Extract Record ID and Current IP from the JSON response
RECORD_ID=$(echo "$RECORD_DATA" | jq -r '.result[0].id // empty')
OLD_IP=$(echo "$RECORD_DATA" | jq -r '.result[0].content // empty')

if [ -z "$RECORD_ID" ]; then
    echo "ERROR: Could not find DNS record for $CF_RECORD_NAME. Check your Zone ID and Name."
    exit 1
fi

# 4. Compare and Update
if [ "$NEW_IP" = "$OLD_IP" ]; then
    echo "IP is still $OLD_IP. No update needed."
else
    echo "IP changed from $OLD_IP to $NEW_IP. Updating Cloudflare..."
    
    UPDATE_RESPONSE=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/dns_records/$RECORD_ID" \
         -H "Authorization: Bearer $CF_API_TOKEN" \
         -H "Content-Type: application/json" \
         --data "{\"type\":\"A\",\"name\":\"$CF_RECORD_NAME\",\"content\":\"$NEW_IP\",\"ttl\":120,\"proxied\":false}")
    
    SUCCESS=$(echo "$UPDATE_RESPONSE" | jq -r '.success')
    
    if [ "$SUCCESS" = "true" ]; then
        echo "SUCCESS: Cloudflare updated to $NEW_IP"
    else
        echo "FAILURE: Update failed. Response: $UPDATE_RESPONSE"
    fi
fi