#!/bin/sh
set -euC

# nfsn-send METHOD REQUEST_URI [KEY VALUE]...

# nfsn-send "GET" "member/$member/sites"
# nfsn-send "POST" "dns/$domain/listRRs" \
#     "name" "" \
#     "type" "MX"

# Arguments.

method="$1" ; shift
request_uri="$1" ; shift

body=""
while [ "$#" -gt "0" ]
do
    key="$1" ; shift
    value="$1" ; shift
    body="${body:-}${body:+"&"}$key=$(printf "%s" "$value" | jq -sRr '@uri')"
done

# Authentication.

login=""
api_key=""
for auth in "${NFSN_CREDENTIALS_PATH:-}" ".nfsn-api" "$HOME/.nfsn-api"
do
    if [ -f "$auth" ]
    then
        login="$(jq -r '."login"' "$auth")"
        api_key="$(jq -r '."api-key"' "$auth")"
        break
    fi
done
login="${NFSN_LOGIN:-"$login"}"
api_key="${NFSN_API_KEY:-"$api_key"}"


if [ -z "${login:-}" ] || [ -z "${api_key:-}" ]
then
    >&2 printf "%s: %s\n" \
        "$0" \
        "Could not find authentication credentials."
    exit 1
fi

# URL.

protocol="https"
host="api.nearlyfreespeech.net"

# protocol="http"
# host="localhost:8080"
# nc -l 8080 &

url="$protocol://$host/$request_uri"

# Data.

body_hash="$(
    printf "%s" "$body" \
    | sha1sum -b \
    | cut -d ' ' -f 1
)"

timestamp="$(
    date "+%s"
)"
salt="$(
    < "/dev/urandom" \
    tr -dc "a-zA-Z0-9" \
    | head -c 16
)"

hash="$(
    printf "%s" \
        "$login;$timestamp;$salt;$api_key;$request_uri;$body_hash" \
    | sha1sum -b \
    | cut -d ' ' -f 1
)"

header="X-NFSN-Authentication: $login;$timestamp;$salt;$hash"

# Request.

response="$(
    curl \
        --silent \
        --request "$method" \
        --header "$header" \
        --data-raw "$body" \
        "$url"
)"

error="$(printf "%s\n" "$response" | jq -r '."error"?')"
debug="$(printf "%s\n" "$response" | jq -r '."debug"?')"

if [ -n "$error" ]
then
    >&2 printf "%s" "$error"
    if [ -n "$debug" ]
    then
        >&2 printf " %s" "$debug"
    fi
    >&2 printf "\n"
    return 1
fi

if [ -n "$response" ]
then
    printf "%s\n" "$response"
fi