#!/bin/sh
set -euC

# nfsn-dns-update DOMAIN NAME TYPE FILTER_REGEX [DATA]...

# nfsn-dns-update "example.com" "git" "A" '' \
#     "$(curl -s "https://api.ipify.org")"

# Arguments.

domain="$1" ; shift
name="$1" ; shift
type="$1" ; shift
filter_regex="$1" ; shift

host="${name:+"$name."}$domain"

data_new_list=""
while [ "$#" -gt "0" ]
do
    data="$1" ; shift
    data_new_list="$(
        printf "%s${data_new_list:+"\n"}%s\n" \
            "${data_new_list:-}" \
            "$data"
    )"
done

# Old data.

data_old_response="$(
    nfsn-send "POST" "/dns/$domain/listRRs" \
        "name" "$name" \
        "type" "$type"
)"
data_old_list="$(
    printf "%s\n" "$data_old_response" \
    | jq -r '
        .[] |
        if ."aux"
        then
            "\(."aux") "
        else
            ""
        end
        +
        "\(."data"?)"
    ' \
    | grep "$filter_regex" \
    || true
)"

# Update.

if [ -n "$data_old_list" ]
then
    printf "%s\n" "$data_old_list" \
    | while IFS= read -r data
    do
        if ! printf "%s\n" "$data_new_list" | grep -qFx "$data"
        then
            printf "Removing data: %s\n" "$data"
            nfsn-send "POST" "/dns/$domain/removeRR" \
                "name" "$name" \
                "type" "$type" \
                "data" "$data"
        fi
    done
fi

if [ -n "$data_new_list" ]
then
    printf "%s\n" "$data_new_list" \
    | while IFS= read -r data
    do
        if ! printf "%s\n" "$data_old_list" | grep -qFx "$data"
        then
            printf "Adding data: %s\n" "$data"
            nfsn-send "POST" "/dns/$domain/addRR" \
                "name" "$name" \
                "type" "$type" \
                "data" "$data"
        else
            printf "Data already present: %s\n" "$data"
        fi
    done
fi