#!/usr/bin/env bash
# Authenticated curl against the NFE Nextcloud, using the app password in the credentials file.
#
#   nc METHOD PATH [extra curl args...]
#   nc GET  /ocs/v2.php/cloud/user
#   nc PROPFIND /remote.php/dav/files/aaron.tushabe/Documents -H 'Depth: 1'
#   nc PUT  /remote.php/dav/files/aaron.tushabe/notes.txt --data-binary @notes.txt
#
# Credentials: ~/.config/nextcloud-api/credentials.env (override with NEXTCLOUD_CREDENTIALS).
# The password is passed to curl on stdin (-K -), so it never shows up in argv, logs or output.
# Works anywhere with bash + curl (macOS, Linux, WSL, Git Bash on Windows).
# Exit 2 = credentials missing (fall back to the browser route, see references/browser-fallback.md).
set -euo pipefail

CRED_FILE="${NEXTCLOUD_CREDENTIALS:-$HOME/.config/nextcloud-api/credentials.env}"

# Read KEY=value from the credentials file without sourcing it (no code execution, tolerates CRLF and quotes).
cred() {
  [[ -f "$CRED_FILE" ]] || return 0
  local v
  v="$(grep -E "^[[:space:]]*$1[[:space:]]*=" "$CRED_FILE" | tail -n1 | cut -d= -f2- | tr -d '\r')" || true
  v="${v#"${v%%[![:space:]]*}"}"; v="${v%"${v##*[![:space:]]}"}"
  v="${v#\"}"; v="${v%\"}"; v="${v#\'}"; v="${v%\'}"
  printf '%s' "$v"
}

NC_URL="${NEXTCLOUD_URL:-$(cred NEXTCLOUD_URL)}"; NC_URL="${NC_URL:-https://nextcloud.nearlyfreeenergy.com}"; NC_URL="${NC_URL%/}"
NC_USER="${NEXTCLOUD_USER:-$(cred NEXTCLOUD_USER)}"
pw="$(cred NEXTCLOUD_APP_PASSWORD)"

if [[ $# -lt 2 ]]; then
  echo "usage: nc METHOD PATH [curl args...]" >&2
  exit 64
fi
method="$1"; path="$2"; shift 2

if [[ -z "$NC_USER" || -z "$pw" ]]; then
  echo "nc: no Nextcloud app password found in $CRED_FILE." >&2
  echo "nc: ask the user to fill in NEXTCLOUD_USER and NEXTCLOUD_APP_PASSWORD there (see SKILL.md 'Setup')." >&2
  exit 2
fi

url="$path"
[[ "$path" == http* ]] || url="${NC_URL}${path}"

headers=(-H 'OCS-APIRequest: true')
# JSON for OCS and app APIs; WebDAV/CalDAV/CardDAV speak XML and set their own types.
case "$path" in
  /ocs/*|/apps/*|/index.php/*) headers+=(-H 'Accept: application/json') ;;
esac

esc_pw="${pw//\\/\\\\}"; esc_pw="${esc_pw//\"/\\\"}"
printf 'user = "%s:%s"\n' "$NC_USER" "$esc_pw" |
  curl -sS -K - --fail-with-body -X "$method" "${headers[@]}" "$url" "$@"
