#!/bin/bash

AKEYLESS_PREFIX=akeyless://
if [ ! -z ${AKEYLESS_API_GW_URL} ] && [ -f ~/.akeyless/latest_token ]; then
  LATEST_PROFILE=$(cat ~/.akeyless/latest_token)
elif [ -d ~/.akeyless/profiles/ ]; then
  LATEST_PROFILE=$(ls -1t ~/.akeyless/profiles/ 2>/dev/null | head -1)
fi

if [ ! -z ${LATEST_PROFILE} ]; then
  ENV_RUNNING_FLAG=~/.akeyless/env_running
  if [ ! -f ${ENV_RUNNING_FLAG} ]; then
    touch ${ENV_RUNNING_FLAG}
    LATEST_PROFILE=${LATEST_PROFILE%".toml"}
    for var in $(env | grep "=${AKEYLESS_PREFIX}" | sed 's/=.*//g')
    do
      if [[ "${!var}" = "${AKEYLESS_PREFIX}"* ]]; then
        SECRET_PATH=${!var#"$AKEYLESS_PREFIX"}
        SECRET_TYPE=$(akeyless describe-item --name "${SECRET_PATH}" --profile ${LATEST_PROFILE} 2>/dev/null | jq -r .item_type)
        [ -z ${SECRET_TYPE} ] && continue
        [[ "${SECRET_TYPE}" == "DYNAMIC_SECRET" ]] && IS_DYNAMIC="dynamic-" || IS_DYNAMIC=""
        [[ "${SECRET_TYPE}" == "ROTATED_SECRET" ]] && IS_ROTATED="rotated-" || IS_ROTATED=""
        NEW_VAL=$(akeyless get-${IS_DYNAMIC}${IS_ROTATED}secret-value --name "${SECRET_PATH}" --profile ${LATEST_PROFILE} 2>/dev/null)
        if [ ! -z "${NEW_VAL}" ]; then
          export $var="${NEW_VAL}"
        fi
      fi
    done
    rm -f ${ENV_RUNNING_FLAG}
  fi
fi
