#!/bin/bash

# ---------------------------------------------------------------------
# Copyright © 2021  Akeyless Security LTD.
#
# All rights reserved
# ----------------------------------------------------------------------

PROFILE_NAME=${PROFILE_NAME:-"default"}
API_GW_URL=${API_GW_URL:-"https://rest.akeyless.io"}
ITEM_NAME=$1 # dynamic secret item as param

function usage() {
	cat <<EOF
Usage: $0 <path-to-dynamic-secret> [--profile <profile-name>] [--host <host>]
Optional arguments:
--profile                    (default: 'default')
--host"
EOF
	exit 1
}

if [ "$ITEM_NAME" == "" ]; then
   usage
fi

until [ -z $2 ]; do
   case $2 in
   --profile)
      PROFILE_NAME=$3
      shift
      ;;
   --host)
      HOST=$3
      shift
      ;;
   * )
      usage
      ;;
   esac
    shift
done

akeyless list-items --profile ${PROFILE_NAME} > /dev/null 2>&1
ACCESS_ID=`cat ~/.akeyless/profiles/${PROFILE_NAME}.toml | grep access_id | tr -d '"' | tr -d "'" | awk '{print $3}'`
TMP_CREDS=`cat ~/.akeyless/.tmp_creds/${PROFILE_NAME}-${ACCESS_ID}`
TOKEN=`curl -s -d "cmd=static-creds-auth&access-id=${ACCESS_ID}" --data-urlencode "creds=${TMP_CREDS}" ${API_GW_URL} | grep token | cut -d '"' -f 4`
if [ "$HOST" == "" ]; then
   curl -s -d "cmd=get-dynamic-secret-value&name=${ITEM_NAME}&token=${TOKEN}" ${API_GW_URL}
else
   curl -s -d "cmd=get-dynamic-secret-value&name=${ITEM_NAME}&host=${HOST}&token=${TOKEN}" ${API_GW_URL}
fi
