#!/bin/bash
CURL="/usr/bin/curl"
SYSCREDS="/etc/default/ngcp-api"
USERCREDS="${HOME}/.ngcp-api"
TOOLS="/usr/share/ngcp-panel-tools/ngcp-api.inc"

usage () {
  cat << EOF
Usage: $0 [OPTIONS] <url>

sends a patch request to NGCP REST API

OPTIONS:
  -h this help
  -v verbose mode
  -f read the input info from a file instead of read stdin
  -m use Header 'Refer: return=minimal'
EOF
  exit 1
}

if [ -z "${APIUSER}" ]; then
  if [ -f "${TOOLS}" ]; then
    # shellcheck source=./tools/ngcp-api.inc
    source "${TOOLS}"

    importcreds "${USERCREDS}" 0600
    if [ -z "${APIUSER}" ]; then
      importcreds "${SYSCREDS}" 0440
      APIUSER="${AUTH_SYSTEM_LOGIN}:${AUTH_SYSTEM_PASSWORD}"
      APIREALM=(-H 'NGCP-UserAgent: NGCP::API::Client')
    fi
  fi
  if [ -z "${APIUSER}" ]; then
    echo "Error: no authentication credentials found" >&2
    exit 1
  fi
fi
CURL_OPTS=()
INPUT=(-T -)
CTYPE="application/json-patch+json"
PREFER="representation"

while getopts "mf:hv" OPTION
do
  case ${OPTION} in
    h)
      usage
      ;;
    f)
      INPUT=()
      FILE_INPUT=(--data-binary "@${OPTARG}")
      if [ ! -f "${OPTARG}" ]; then
        echo "No '${OPTARG}' file found"
        usage
      fi
      ;;
    m)
      PREFER="minimal"
      ;;
    v)
      CURL_OPTS+=(--verbose)
      ;;
    ?)
      usage
      ;;
  esac
done
shift $((OPTIND - 1))

URL="$1"
if [ -z "${URL}" ] ; then
  usage
fi
validateurl "$URL"

${CURL} -i "${CURL_OPTS[@]}" -X PATCH \
  "${APIREALM[@]}" \
  -H 'Connection: close' -H "Prefer: return=${PREFER}" \
  -H "Content-Type: ${CTYPE}" \
  --user "${APIUSER}" --insecure "${FILE_INPUT[@]}" "${URL}" "${INPUT[@]}"
