#!/bin/sh
set -eu

if [ -n "${VAULT_ENV_FILE:-}" ]; then
  if [ -f "${VAULT_ENV_FILE}" ]; then
    # shellcheck disable=SC1090
    . "${VAULT_ENV_FILE}"
  else
    echo "Vault env file not found: ${VAULT_ENV_FILE}" >&2
    exit 1
  fi
fi

if [ -n "${VAULT_COPY_FILES:-}" ]; then
  old_ifs="$IFS"
  IFS=','
  for pair in ${VAULT_COPY_FILES}; do
    src="${pair%%:*}"
    dest="${pair#*:}"
    if [ -z "${src}" ] || [ -z "${dest}" ]; then
      echo "Vault copy entry malformed: ${pair}" >&2
      exit 1
    fi
    if [ ! -f "${src}" ]; then
      echo "Vault file not found: ${src}" >&2
      exit 1
    fi
    mkdir -p "$(dirname "${dest}")"
    cp "${src}" "${dest}"
  done
  IFS="$old_ifs"
fi

exec "$@"
