#!/bin/sh

if ! which jq > /dev/null; then
    echo "WARNING: jq is missing" >& 2
fi

fp_login()
{
    local HOST="$1"
    local USERNAME="$2"
    local PASSWORD="$3"

    if [ -z "${HOST}" ] || [ -z "${USERNAME}" ]; then
        echo "ERROR: must specify host and username" >& 2
        echo "Usage: fp_login HOST USERNAME [PASSWORD]" >& 2
        return 1
    fi

    curl -k https://${HOST}/api/v0/login -b ${HOST}.cookies -c ${HOST}.cookies \
        -d '{"username":"'"${USERNAME}"'", "password":"'"${PASSWORD}"'"}' \
        -H "Content-Type: application/json" -o ${HOST}.login

    if [ "$(jq -r '.["status"]' ${HOST}.login)" != "success" ]; then
        echo "ERROR: $(cat ${HOST}.login)" >& 2
        return 2
    else
        echo "DONE"
    fi
}

fp_alive()
{
    local HOST="$1"

    if [ -z "${HOST}" ]; then
        echo "ERROR: must specify host" >& 2
        echo "Usage: fp_alive HOST" >& 2
        return 1
    fi

    fp_get "${HOST}" /api/v0/alive > ${HOST}.login
    if [ "$(jq -r '.["status"]' ${HOST}.login)" != "success" ]; then
        echo "ERROR: $(cat ${HOST}.login)" >& 2
        return 2
    else
        echo "DONE"
    fi
}

fp_get()
{
    local HOST="$1"
    local URLPATH="$2"

    if [ -z "${HOST}" ] || [ -z "${URLPATH}" ]; then
        echo "ERROR: must specify host and path" >& 2
        echo "Usage: fp_get HOST PATH" >& 2
        return 1
    fi

    curl -k https://${HOST}/${URLPATH} -b ${HOST}.cookies -c ${HOST}.cookies
}

fp_post()
{
    local HOST="$1"
    local URLPATH="$2"
    local DATA="$3"

    if [ -z "${HOST}" ] || [ -z "${URLPATH}" ]; then
        echo "ERROR: must specify host and path" >& 2
        echo "Usage: fp_post HOST PATH [DATA]" >& 2
        return 1
    fi

    local CSRF_HEADER="$(jq -r '.["csrf-token-http-header"]' ${HOST}.login)"
    local CSRF_VALUE="$(jq -r '.["csrf-token"]' ${HOST}.login)"

    if [ -n "${DATA}" ]; then
        curl -k https://${HOST}/${URLPATH} -b ${HOST}.cookies -c ${HOST}.cookies \
             -e https://${HOST}/ \
             -H "${CSRF_HEADER}: ${CSRF_VALUE}" \
             -d "${DATA}" -H "Content-Type: application/json"
    else
        curl -k https://${HOST}/${URLPATH} -b ${HOST}.cookies -c ${HOST}.cookies \
             -e https://${HOST}/ \
             -H "${CSRF_HEADER}: ${CSRF_VALUE}" \
             -X POST
    fi
}

fp_post_raw()
{
    local HOST="$1"
    local URLPATH="$2"

    if [ -z "${HOST}" ] || [ -z "${URLPATH}" ]; then
        echo "ERROR: must specify host and path" >& 2
        echo "Usage: fp_post HOST PATH [DATA]" >& 2
        return 1
    fi
    shift 2

    local CSRF_HEADER="$(jq -r '.["csrf-token-http-header"]' ${HOST}.login)"
    local CSRF_VALUE="$(jq -r '.["csrf-token"]' ${HOST}.login)"

    curl -k https://${HOST}/${URLPATH} -b ${HOST}.cookies -c ${HOST}.cookies \
         -e https://${HOST}/ \
         -H "${CSRF_HEADER}: ${CSRF_VALUE}" \
         -X POST "$@"
}
