#!/bin/bash
# Poor man's keep command line
#Global variables
httpcommand=$(echo "$1" | tr '[:lower:]' '[:upper:]')
keep=http://localhost:8880
user="KEEP Admin"
apipath=api

# Login function
execute_login() {
   # Login to KEEP remote
   read -p "server [$keep]:" server
   read -p "Username [$user]: " uservar
   read -sp "Password: " passvar
   server=${server:-$keep}
   uservar=${uservar:-$user}
   echo 
   echo accessing $server as $uservar
   echo
   dataraw="{\"username\" : \"${uservar}\", \"password\" : \"${passvar}\"}"
   token=$(curl --location --request POST "${server}/api/v1/auth" \
   --header 'Content-Type: application/json' \
   --data-raw "${dataraw}" |  jq -r  '.bearer')
   echo $token
   echo token=$token > $TMPDIR/keep.login
   echo server=$server >> $TMPDIR/keep.login
   exit 0
}

# Logout, just remove the token
execute_logout() {
    echo User logged out > $TMPDIR/keep.login
    rm -f $TMPDIR/keep.login
    echo User logged out
    exit 0
}

# Make a call to keeep
execute_http() {
if [ ! -f $TMPDIR/keep.login ]; then
	echo "You need to login first with keep login"
	exit 1
fi
export $(cat $TMPDIR/keep.login | xargs)
 httpcommand=$(echo "$1" | tr '[:lower:]' '[:upper:]')
 shift
 curl -s -X ${httpcommand} --fail --insecure -H "Authorization: Bearer ${token}" -H "Content-Type: application/json" ${server}/${apipath}/$@
 if [ $? -ne 0 ]; then
   echo "Command $httpcommand failed!"
   exit 1
 fi
 exit 0
}

execute_help() {
  echo "Usage keep [login|logout|help]"
  echo "      keep [get|post|put|patch|delete] URL PAYLOAD"
  echo " e.g. keep login"
  echo "      keep get v1/scopes"
  echo "      keep get pim-v1/inbox" 
  echo "Hints:"
  echo '      "keep get" without parameters - returns list of APIs'
  echo "      common APIs: v1,admin-v1,pim-v1,poi-v1,setup-v1"
  echo '      "keep get [api]/schema/[schema-json-fiel from keep get]" returns the OpenAPI spec for that API'
  echo " e.g. keep get v1/schema/openapi.basis.json"
  echo '      using "| jq" after a command returns pretty printed JSON (jq installed separately)'
}

if [ -z "$1" ]; then
  execute_help;
  exit 1
fi

if [[ "$httpcommand" == "LOGIN" ]]; then
  execute_login;
fi

if [[ "$httpcommand" == "LOGOUT" ]]; then
  execute_logout;
fi

if [[ "$httpcommand" == "HELP" ]]; then
  execute_help;
  exit 0
fi

# All other cases
execute_http $@
