#!/bin/bash
# shellcheck disable=SC1090 # https://www.shellcheck.net/wiki/SC1090
# shellcheck disable=SC2154 # https://www.shellcheck.net/wiki/SC2154
# shellcheck disable=SC2016 # https://www.shellcheck.net/wiki/SC2016

# main variables
# using same config file than for Golang script
OVH_CONF="${OVH_CONF:-../golang/ovh.conf}"
OVH_API_VERSION="1.0"
#OUTPUT="${OUTPUT:-json}"

# source all ovh keys
source <( grep '=' "${OVH_CONF}" )

# Create ENDPOINT
case "${endpoint}" in
  ovh-eu) ENDPOINT="https://eu.api.ovh.com/${OVH_API_VERSION}" ;;
  ovh-us) ENDPOINT="https://us.api.ovh.com/${OVH_API_VERSION}" ;;
  ovh-ca) ENDPOINT="https://ca.api.ovh.com/${OVH_API_VERSION}" ;;
  *) echo "${endpoint} is not yet supported" ; exit ;;
esac

# Signing process
# @"method" "url" "post_data" "timestamp"
TIME=$( curl -s "${ENDPOINT}/auth/time" )

# Method
# ovh-bash get vps
HTTP_METHOD="${1:?need a http method}"
HTTP_QUERY="${ENDPOINT}/${2:?need a query}"
HTTP_PAYLOAD="${3}"

CLEAR_SIGN="${application_secret}+${consumer_key}+${HTTP_METHOD^^}+${HTTP_QUERY}+${HTTP_PAYLOAD}+${TIME}"
SIG='$1$'$( echo -n "${CLEAR_SIGN}" | sha1sum - | cut -d' ' -f1 )

# curl call
curl -sL -X "${HTTP_METHOD^^}" \
	-H "Content-Type:application/json;charset=utf-8" \
	-H "X-Ovh-Application:${application_key}" \
	-H "X-Ovh-Timestamp:${TIME}" \
	-H "X-Ovh-Signature:${SIG}" \
	-H "X-Ovh-Consumer:${consumer_key}" \
	--data "${HTTP_PAYLOAD}" "${HTTP_QUERY}" \
	| jq '.'

exit $?