#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Korkarn Kovitanupong
set -o pipefail
export LC_ALL=C
umask 077

config_dir=/etc/cloudflare-ddns
apply=false
if [[ "${1:-}" == --apply ]]; then
    apply=true
    shift
fi

if (( $# == 0 )); then
    printf 'Usage: %s [--apply] PROFILE [PROFILE ...]\n' "$0" >&2
    exit 2
fi

for profile in "$@"; do
    if [[ ! "$profile" =~ ^[a-z0-9][a-z0-9_-]*$ ]]; then
        printf 'Invalid profile name: %s\n' "$profile" >&2
        exit 2
    fi
done

current_ip=$(curl -q -4 -fsS --connect-timeout 10 --max-time 20 https://api.ipify.org) || {
    echo 'Could not read public IPv4' >&2; exit 1;
}
if ! python3 -c 'import ipaddress,sys; a=ipaddress.IPv4Address(sys.argv[1]); sys.exit(not a.is_global or a.is_multicast)' "$current_ip" 2>/dev/null; then
    echo 'Invalid public IPv4; DNS unchanged' >&2
    exit 1
fi

dns_api() {
    local url=$1
    shift
    # Pass the bearer token through stdin, not as a command-line argument.
    printf 'Authorization: Bearer %s\n' "$token" |
        curl -q -fsS --connect-timeout 10 --max-time 30 \
            --header @- --header 'Content-Type: application/json' "$@" "$url"
}

update_profile() {
    local profile=$1 zone_id record_name token endpoint response id old_ip payload
    zone_id=$(<"$config_dir/$profile.zone") || return 1
    record_name=$(<"$config_dir/$profile.name") || return 1
    token=$(<"$config_dir/$profile.token") || return 1
    if [[ ! "$zone_id" =~ ^[[:xdigit:]]{32}$ ||
          ! "$record_name" =~ ^[a-z0-9][a-z0-9.-]*\.[a-z0-9-]+$ ||
          ! "$token" =~ ^[A-Za-z0-9_-]+$ ]]; then
        echo "$profile: invalid .zone, .name or .token file" >&2
        return 1
    fi

    endpoint="https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records"
    response=$(dns_api "$endpoint" --get --data-urlencode 'type=A' \
        --data-urlencode "name.exact=$record_name" \
        --data-urlencode 'match=all' --data-urlencode 'per_page=100') || return 1

    if ! jq -e --arg name "$record_name" '
        .success == true and (.result | type == "array" and length == 1)
        and (.result[0] | .type == "A" and .name == $name
             and (.id | type == "string" and test("^[0-9a-fA-F]{32}$"))
             and (.content | type == "string"))
        ' <<< "$response" >/dev/null; then
        echo "$profile: expected exactly one A record for $record_name" >&2
        return 1
    fi
    id=$(jq -er '.result[0].id' <<< "$response") || return 1
    old_ip=$(jq -er '.result[0].content' <<< "$response") || return 1

    if [[ "$old_ip" == "$current_ip" ]]; then
        echo "$record_name up to date"
        return 0
    fi
    if [[ "$apply" == false ]]; then
        echo "$record_name would update (preview)"
        return 0
    fi

    payload=$(jq -nc --arg ip "$current_ip" '{content:$ip}') || return 1
    if ! dns_api "$endpoint/$id" --request PATCH --data "$payload" |
        jq -e --arg ip "$current_ip" --arg id "$id" \
            '.success == true and .result.id == $id and .result.content == $ip' >/dev/null; then
        echo "$record_name update failed" >&2
        return 1
    fi
    echo "$record_name updated"
}

status=0
for profile in "$@"; do
    update_profile "$profile" || { echo "$profile failed" >&2; status=1; }
done
echo "DDNS finished at $(date -Is), status=$status"
exit "$status"
