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

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

AUTH_FILE="creds/joker_com_dyndns_creds.txt"
if [[ -f "$AUTH_FILE" ]]; then
  JOKER_AUTH="$(cat "$AUTH_FILE")"
elif [[ -n "${JOKER_DYNDNS_USERNAME:-}" && -n "${JOKER_DYNDNS_PASSWORD:-}" ]]; then
  JOKER_AUTH="${JOKER_DYNDNS_USERNAME}:${JOKER_DYNDNS_PASSWORD}"
else
  echo "Joker DYNDNS credentials missing (file $AUTH_FILE or env JOKER_DYNDNS_USERNAME/PASSWORD)" >&2
  exit 1
fi
TARGET_IP="${TARGET_IP:-157.180.66.64}"
LOGS_HOST="${LOGS_HOST:-logs.lomavuokraus.fi}"

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