#!/usr/bin/env bash

# Qortal defaults
host="localhost"
port=12393

if [ -z "$*" ]; then
	echo "Usage:"
	echo
	echo "Host/update data:"
	echo "qdata [PUT/PATCH] [service] [name] [dirpath]"
	echo
	echo "Fetch data:"
	echo "qdata GET [service] [name] [filepath] <rebuild>"
	echo
	exit
fi

method=$1
service=$2
name=$3

if [ -z "${method}" ]; then
  echo "Error: missing method"; exit
fi
if [ -z "${service}" ]; then
  echo "Error: missing service"; exit
fi
if [ -z "${name}" ]; then
  echo "Error: missing name"; exit
fi


if [[ "${method}" == "PUT" || "${method}" == "PATCH" ]]; then
  directory=$4

  if [ -z "${directory}" ]; then
    echo "Error: missing directory"; exit
  fi
  if [ -z "${QORTAL_PRIVKEY}" ]; then
    echo "Error: missing private key. Set it by running: export QORTAL_PRIVKEY=privkeyhere"; exit
  fi

  echo "Creating transaction - this can take a while..."
  tx_data=$(curl --silent --insecure -X ${method} "http://${host}:${port}/arbitrary/${service}/${name}" -d "${directory}")
  if [[ "${tx_data}" == *"error"* || "${tx_data}" == *"ERROR"* ]]; then
    echo "${tx_data}"; exit
  fi

  echo "Signing..."
  signed_tx_data=$(curl --silent --insecure -X POST "http://${host}:${port}/transactions/sign" -H  "Content-Type: application/json" -d "{\"privateKey\":\"${QORTAL_PRIVKEY}\",\"transactionBytes\":\"${tx_data}\"}")
  if [[ "${signed_tx_data}" == *"error"* || "${signed_tx_data}" == *"ERROR"* ]]; then
    echo "${signed_tx_data}"; exit
  fi

  echo "Broadcasting..."
  success=$(curl --silent --insecure -X POST "http://${host}:${port}/transactions/process" -H  "Content-Type: text/plain" -d "${signed_tx_data}")
  if [[ "${success}" == "true" ]]; then
    echo "Transaction broadcast successfully"
  else
    echo "Error when broadcasting transaction. Please try again."
    echo "Response: ${success}"
  fi

elif [[ "${method}" == "GET" ]]; then
  filepath=$4
  rebuild=$5

  if [ -z "${filepath}" ]; then
    echo "Error: missing filepath. Please supply the relative path to a file within the data structure."; exit
  fi

  if [ -z "${rebuild}" ]; then
    rebuild="false"
  fi

  response=$(curl --silent --insecure -X GET "http://${host}:${port}/arbitrary/${service}/${name}?rebuild=${rebuild}&filepath=${filepath}")
  if [ -z "${response}" ]; then
    echo "Empty response from ${host}:${port}"
  fi
  if [[ "${response}" == *"error"* || "${response}" == *"ERROR"* ]]; then
    echo "${response}"; exit
  fi

  echo "${response}"

fi