#!/bin/bash
# Fjall Secrets Resolver Wrapper
#
# Invoked by AWS_LAMBDA_EXEC_WRAPPER before the Lambda runtime starts.
# Calls the Node.js resolver to fetch secrets from the AWS Parameters and
# Secrets Extension, then execs into the original runtime bootstrap.
#
# The resolver outputs `export KEY='value'` lines which we eval to inject
# secrets as environment variables visible to the handler.

set -euo pipefail

# Only run resolver if secrets are configured
if [ -n "${SSM_SECRET_NAMES:-}" ] || env | grep -q '_SECRET_ARN='; then
  RESOLVER_OUTPUT=$(/var/lang/bin/node /opt/bin/resolve-secrets.mjs)
  if [ -n "$RESOLVER_OUTPUT" ]; then
    # Validate each line matches `export NAME='...'` before eval to prevent
    # accidental code execution if the resolver ever emits unexpected output
    while IFS= read -r line; do
      if [[ "$line" =~ ^export\ [a-zA-Z_][a-zA-Z0-9_]*= ]]; then
        eval "$line"
      else
        echo "[fjall-resolver] Unexpected output from resolver: ${line:0:80}" >&2
        exit 1
      fi
    done <<< "$RESOLVER_OUTPUT"
  fi
fi

exec "$@"
