#!/usr/bin/env bash
# Thin wrapper around the Nginx Proxy Manager REST API.
#   source npm-api.sh; npm_login; npm_get /api/nginx/proxy-hosts | jq .
# Env: NPM_URL (default http://192.168.12.52:81), NPM_USER, NPM_PASS
#      (or NPM_CREDS_FILE, default /root/npm-admin.txt with "user\npassword" when run on the edge VM)
NPM_URL="${NPM_URL:-http://192.168.12.52:81}"
npm_login() {
  if [ -z "${NPM_USER:-}" ] && [ -f "${NPM_CREDS_FILE:-/root/npm-admin.txt}" ]; then
    NPM_USER=$(sed -n 1p "${NPM_CREDS_FILE:-/root/npm-admin.txt}"); NPM_PASS=$(sed -n 2p "${NPM_CREDS_FILE:-/root/npm-admin.txt}")
  fi
  NPM_TOKEN=$(curl -fsS "$NPM_URL/api/tokens" -H 'Content-Type: application/json' \
    -d "$(jq -n --arg i "$NPM_USER" --arg s "$NPM_PASS" '{identity:$i, secret:$s}')" | jq -r .token)
  [ -n "$NPM_TOKEN" ] && [ "$NPM_TOKEN" != null ] || { echo "login failed" >&2; return 1; }
  export NPM_TOKEN
}
npm_get()    { curl -fsS "$NPM_URL$1" -H "Authorization: Bearer $NPM_TOKEN"; }
npm_post()   { curl -fsS "$NPM_URL$1" -H "Authorization: Bearer $NPM_TOKEN" -H 'Content-Type: application/json' -d "$2"; }
npm_put()    { curl -fsS -X PUT "$NPM_URL$1" -H "Authorization: Bearer $NPM_TOKEN" -H 'Content-Type: application/json' -d "$2"; }
npm_delete() { curl -fsS -X DELETE "$NPM_URL$1" -H "Authorization: Bearer $NPM_TOKEN"; }
# npm_cert_upload <nice_name> <cert.pem> <key.pem>  -> certificate id
npm_cert_upload() {
  local id
  id=$(npm_post /api/nginx/certificates "$(jq -n --arg n "$1" '{provider:"other", nice_name:$n}')" | jq -r .id)
  curl -fsS "$NPM_URL/api/nginx/certificates/$id/upload" -H "Authorization: Bearer $NPM_TOKEN" \
    -F "certificate=@$2" -F "certificate_key=@$3" >/dev/null
  echo "$id"
}
# npm_cert_id_by_name <nice_name>
npm_cert_id_by_name() { npm_get /api/nginx/certificates | jq -r --arg n "$1" '.[] | select(.nice_name==$n) | .id' | head -1; }
# npm_host_id_by_domain <domain>
npm_host_id_by_domain() { npm_get /api/nginx/proxy-hosts | jq -r --arg d "$1" '.[] | select(.domain_names | index($d)) | .id' | head -1; }
