#!/bin/sh

# https://ounapuu.ee/posts/2026/05/06/self-host-at-home/

# Load environment variables
. /etc/ddns/.env

API_BASE="https://api.zone.eu/v2/dns"
API_ERROR=0

# Get WAN IPv4
get_ipv4() {
    ip -4 addr show eth0.2 | awk '/inet / {print $2}' | cut -d'/' -f1 | head -n1
}

get_ipv6() {
    awk '/myservershostname/ && /^2001:/' /tmp/hosts/odhcpd.hosts.lan | awk '{print $1}'
}

# Get current DNS record (returns empty string on error, sets global error flag)
get_current_dns() {
    local domain=$1
    local type=$2
    local id=$3
    local response

    API_ERROR=0
    response=$(curl -sf -u "$BASIC_AUTH_USERNAME:$BASIC_AUTH_PASSWORD" \
        "$API_BASE/$domain/$type/$id" 2>/dev/null)

    if [ $? -ne 0 ] || [ -z "$response" ]; then
        API_ERROR=1
        return 1
    fi

    echo "$response" | sed -n 's/.*"destination":"\([^"]*\)".*/\1/p' | head -n1
}

# Update DNS record
update_dns() {
    local domain=$1
    local type=$2
    local id=$3
    local ip=$4
    local name=$5

    local fqdn="${name:+$name.}$domain"

    curl -s -u "$BASIC_AUTH_USERNAME:$BASIC_AUTH_PASSWORD" \
        -X PUT \
        -d "destination=$ip&name=$fqdn" \
        "$API_BASE/$domain/$type/$id" > /dev/null
}

# Perform update if IP changed
perform_update() {
    local name=$1
    local domain=$2
    local id=$3
    local actual_ip=$4
    local type=$5

    echo "Checking $type record: ${name:+$name.}$domain (ID: $id)"

    local current_ip
    current_ip=$(get_current_dns "$domain" "$type" "$id")

    if [ "$API_ERROR" -eq 1 ]; then
        echo "  ERROR: Failed to get current DNS record, skipping update"
        echo
        return 1
    fi

    echo "  Current: $current_ip"
    echo "  Actual:  $actual_ip"

    if [ "$current_ip" != "$actual_ip" ]; then
        echo "  IP changed, updating..."
        update_dns "$domain" "$type" "$id" "$actual_ip" "$name"
        echo "  Updated."
    else
        echo "  No change."
    fi
    echo
}

# Main execution
IPV4=$(get_ipv4)
if [ -n "$IPV4" ]; then
    echo "IPv4: $IPV4"
    perform_update "subdomain" "ounpauu.ee" 123456 "$IPV4" "a"
    perform_update "" "ounapuu.ee" 123457 "$IPV4" "a"
else
    echo "ERROR: Could not determine IPv4 address"
fi

IPV6=$(get_ipv6)
if [ -n "$IPV6" ]; then
    echo "IPv6: $IPV6"
    perform_update "subdomain" "ounapuu.ee" 123458 "$IPV6" "aaaa"
    perform_update "" "xn--unapuu-oxa.ee" 123459 "$IPV6" "aaaa"
else
    echo "ERROR: Could not determine IPv6 address for lattepanda"
fi

echo "Done."