#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")/.."

AUTH_FILE="creds/joker_com_dyndns_creds.txt"
if [[ ! -f "$AUTH_FILE" ]]; then
  echo "Joker DYNDNS credentials missing at $AUTH_FILE" >&2
  exit 1
fi

JOKER_AUTH="$(cat "$AUTH_FILE")"
TARGET_IP="${TARGET_IP:-157.180.66.64}"
TEST_HOST="${TEST_HOST:-test.lomavuokraus.fi}"
TEST_API_HOST="${TEST_API_HOST:-apitest.lomavuokraus.fi}"

update_host() {
  local host="$1"
  echo "Updating $host -> $TARGET_IP"
  local resp
  resp="$(curl -sS -u "$JOKER_AUTH" "https://svc.joker.com/nic/update?hostname=${host}&myip=${TARGET_IP}")"
  echo "$resp"
  if [[ "$resp" != good* && "$resp" != nochg* ]]; then
    echo "DNS update failed for $host (response: $resp)" >&2
    exit 1
  fi
}

update_host "$TEST_HOST"
update_host "$TEST_API_HOST"
