#!/usr/bin/env bash

set -e

listFile=shell_test_list.json

case $1 in
	"store")
		in=$(</dev/stdin)
		server=$(echo "$in" | jq --raw-output ".ServerURL")
		serverHash=$(echo "$server" | sha1sum - | awk '{print $1}')

		username=$(echo "$in" | jq --raw-output ".Username")
		password=$(echo "$in" | jq --raw-output ".Secret")
		echo "{ \"Username\": \"${username}\", \"Secret\": \"${password}\" }" > $TEMP/$serverHash
		# add the server to the list file
		if [[ ! -f $TEMP/$listFile ]]; then
			echo "{ \"${server}\": \"${username}\" }" > $TEMP/$listFile
		else
			list=$(<$TEMP/$listFile)
			echo "$list" | jq ". + {\"${server}\": \"${username}\"}" > $TEMP/$listFile
		fi
		;;
	"get")
		in=$(</dev/stdin)
		serverHash=$(echo "$in" | sha1sum - | awk '{print $1}')
		if [[ ! -f $TEMP/$serverHash ]]; then
			echo "credentials not found in native keychain"
			exit 1
		fi
		payload=$(<$TEMP/$serverHash)
		echo "$payload"
		;;
	"erase")
		in=$(</dev/stdin)
		serverHash=$(echo "$in" | sha1sum - | awk '{print $1}')
		rm -f $TEMP/$serverHash

		# Remove the server from the list
		list=$(<$TEMP/$listFile)
		echo "$list" | jq "del(.[\"${in}\"])" > $TEMP/$listFile
		;;
	"list")
		if [[ ! -f $TEMP/$listFile ]]; then
			echo "{}"
		else
			payload=$(<$TEMP/$listFile)
			echo "$payload"
		fi
		;;
	*)
		echo "unknown credential option"
		exit 1
		;;
esac
