#!/usr/bin/env sh
# dns_urlpath.sh — acme.sh DNS-01 plugin for Urlpath DNS (dns.urlpath.cloud)
#
# Publishes _acme-challenge TXT records through the Urlpath DNS customer API,
# so any zone hosted at Urlpath DNS can get free certificates from Let's
# Encrypt or ZeroSSL — wildcards included. Your API key stays on your machine.
#
# Setup (Starter plan or up — API access is a Starter+ feature):
#   1. Panel → Profile → API keys → Create API key (access level: manager)
#   2. Install this file as ~/.acme.sh/dnsapi/dns_urlpath.sh
#
# Issue a cert:
#   export UPATH_Token="upat_..."
#   acme.sh --issue --dns dns_urlpath -d example.com -d '*.example.com'
#
# Optional: export UPATH_Panel="https://dnscp.urlpath.cloud" (the default).
# The token is remembered in ~/.acme.sh/account.conf for unattended renewals.
#
# Requires: curl. No jq needed.

UPATH_Panel="${UPATH_Panel:-https://dnscp.urlpath.cloud}"
UPATH_Api="${UPATH_Panel%/}/api/v1"

# acme.sh supplies _info/_err/_saveaccountconf when this file is sourced from
# its dnsapi directory; keep standalone runs working without shadowing them.
command -v _info >/dev/null 2>&1 || _info() { echo "INFO: $*"; }
command -v _err >/dev/null 2>&1 || _err() { echo "ERROR: $*" >&2; return 1; }

_urlpath_conf() { # persist + reload a setting when running under acme.sh
  key=$1 val=$2
  if command -v _saveaccountconf >/dev/null 2>&1; then
    [ -n "$val" ] && _saveaccountconf "$key" "$val"
    return 0
  fi
  return 0
}

_urlpath_zone() { # echo the account zone suffix-matching $1 (longest wins)
  _ud=$1
  _uresp=$(curl -sf -H "Authorization: Bearer $UPATH_Token" "$UPATH_Api/domains") || {
    _err "cannot list zones at $UPATH_Api/domains — check UPATH_Token/UPATH_Panel"
    return 1
  }
  _uz=""
  for _z in $(printf '%s' "$_uresp" | grep -o '"name":"[^"]*"' | sed 's/^"name":"//;s/"$//'); do
    case "$_ud" in
      "$_z"|*"."$_z) [ "${#_z}" -gt "${#_uz}" ] && _uz=$_z ;;
    esac
  done
  [ -n "$_uz" ] || { _err "'$_ud' does not match any zone on this Urlpath account"; return 1; }
  printf '%s' "$_uz"
}

dns_urlpath_add() {
  fulldomain=$1
  txtvalue=$2

  UPATH_Token="${UPATH_Token:-}"
  if [ -z "$UPATH_Token" ] && command -v _readaccountconf >/dev/null 2>&1; then
    UPATH_Token=$(_readaccountconf UPATH_Token)
  fi
  if [ -z "$UPATH_Token" ]; then
    _err "UPATH_Token is not set — export it (panel → Profile → API keys)"
    return 1
  fi
  _urlpath_conf UPATH_Token "$UPATH_Token"
  _urlpath_conf UPATH_Panel "$UPATH_Panel"

  _uzone=$(_urlpath_zone "$fulldomain") || return 1
  _uname=${fulldomain%."$_uzone"}
  [ -z "$_uname" ] && _uname="@"

  _ubody="{\"name\":\"$_uname\",\"type\":\"TXT\",\"value\":\"$txtvalue\",\"ttl\":60}"
  _ucode=$(curl -s -o /dev/null -w '%{http_code}' -X POST \
    -H "Authorization: Bearer $UPATH_Token" -H "Content-Type: application/json" \
    -d "$_ubody" "$UPATH_Api/domains/$_uzone/records")
  case $_ucode in
    200|201) _info "TXT $_uname.$_uzone published (zone $_uzone)" ;;
    409) _info "TXT $_uname.$_uzone already present" ;;
    *) _err "adding TXT on $_uzone failed — HTTP $_ucode"; return 1 ;;
  esac
  return 0
}

dns_urlpath_rm() {
  fulldomain=$1
  txtvalue=$2

  UPATH_Token="${UPATH_Token:-}"
  if [ -z "$UPATH_Token" ] && command -v _readaccountconf >/dev/null 2>&1; then
    UPATH_Token=$(_readaccountconf UPATH_Token)
  fi
  [ -n "$UPATH_Token" ] || { _info "rm: no token, skipping cleanup"; return 0; }

  _uzone=$(_urlpath_zone "$fulldomain") || return 0
  _uname=${fulldomain%."$_uzone"}
  [ -z "$_uname" ] && _uname="@"

  _urecs=$(curl -sf -H "Authorization: Bearer $UPATH_Token" \
    "$UPATH_Api/domains/$_uzone/records") || { _info "rm: cannot list records, skipping"; return 0; }
  # records arrive as compact JSON with id before value in every object
  _uids=$(printf '%s' "$_urecs" | tr '{' '\n' \
    | grep -F "\"value\":\"$txtvalue\"" \
    | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
  [ -n "$_uids" ] || { _info "rm: challenge record already gone"; return 0; }
  for _uid in $_uids; do
    _ucode=$(curl -s -o /dev/null -w '%{http_code}' -X DELETE \
      -H "Authorization: Bearer $UPATH_Token" \
      "$UPATH_Api/domains/$_uzone/records/$_uid")
    if [ "$_ucode" = "204" ] || [ "$_ucode" = "200" ]; then
      _info "TXT $_uname.$_uzone removed (record $_uid)"
    else
      _info "rm: record $_uid returned HTTP $_ucode (leaving it)"
    fi
  done
  return 0
}
