#!/bin/bash
source /home/sij/.GLOBAL_VARS

service="https://am.i.mullvad.net/ip"
# Obtain the current public IP address
#current_ip=$(ssh -n sij@10.13.37.10 curl -s $service)
current_ip=$(curl -s $service)
last_ip=$(cat /home/sij/.services/ip.txt)
api_token=$CF_API_KEY

# Path to the JSON file with zone IDs, subdomains, and DNS IDs mappings
json_file="/home/sij/.services/cf_domains.json"

force_update=false

# Parse command line arguments for --force flag
while [[ "$#" -gt 0 ]]; do
    case $1 in
        -f|--force) force_update=true ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

# Temporary file to store update results
temp_file=$(mktemp)

# Function to update DNS records
update_dns_record() {
    zone_id=$1
    subdomain=$2
    dns_id=$3
    update_result=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$dns_id" \
         -H "Authorization: Bearer $api_token" \
         -H "Content-Type: application/json" \
         --data "{\"type\":\"A\",\"name\":\"$subdomain\",\"content\":\"$current_ip\",\"ttl\":120,\"proxied\":true}")
    echo "$update_result" >> "$temp_file"
}

# Check if IP has changed or --force flag is used
if [ "$current_ip" != "$last_ip" ] || [ "$force_update" = true ]; then
    echo $current_ip > /home/sij/.services/ip.txt
    # Iterate through each domain in the JSON
    /home/sij/miniforge3/bin/jq -r '.[] | .zone_id as $zone_id | .subdomains | to_entries[] | [$zone_id, .key, .value] | @tsv' $json_file |
    while IFS=$'\t' read -r zone_id subdomain dns_id; do
        update_dns_record "$zone_id" "$subdomain" "$dns_id"
    done
    # Combine all update results into a single JSON array
    /home/sij/miniforge3/bin/jq -s '.' "$temp_file"
    # Remove the temporary file
    rm "$temp_file"
else
    echo "IP address has not changed from ${last_ip}. No action taken."
fi