#!/bin/bash

set -e

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

		username=$(echo "$in" | jq --raw-output ".Username")
		password=$(echo "$in" | jq --raw-output ".Secret")
		echo "{ \"Username\": \"${username}\", \"Secret\": \"${password}\" }" > $TEMP/$server
		;;
	"get")
		in=$(</dev/stdin)
		server=$(echo "$in" | sha1sum - | awk '{print $1}')
		if [[ ! -f $TEMP/$server ]]; then
			echo "credentials not found in native keychain"
			exit 1
		fi
		payload=$(<$TEMP/$server)
		echo "$payload"
		;;
	"erase")
		in=$(</dev/stdin)
		server=$(echo "$in" | sha1sum - | awk '{print $1}')
		rm -f $TEMP/$server
		;;
	*)
		echo "unknown credential option"
		exit 1
		;;
esac
