#!/bin/sh set -e # --- Configuration (from Environment Variables) --- # UPDATED: Set the default APP_NAME for logging APP_NAME="${APP_NAME:-sops-decrypt}" GPG_KEY_PATH="${GPG_KEY_PATH:-/run/secrets/gpg_key}" GPG_PASSPHRASE_PATH="${GPG_PASSPHRASE_PATH:-/run/secrets/gpg_passphrase}" SOPS_INPUT_DIR="${SOPS_INPUT_DIR:-/in}" SOPS_OUTPUT_DIR="${SOPS_OUTPUT_DIR:-/out}" SOPS_VERBOSE="${SOPS_VERBOSE:-false}" # --- Script Logic --- echo "✅ $APP_NAME: Configuration materializer started." if [ "$SOPS_VERBOSE" = "true" ]; then echo "🐞 $APP_NAME: VERBOSE mode enabled." fi echo "➡️ $APP_NAME: Input Dir: '$SOPS_INPUT_DIR', Output Dir: '$SOPS_OUTPUT_DIR'" # --- GPG Key Import and Unlocking --- echo "🔄 $APP_NAME: Starting GPG Agent..." unset GPG_AGENT_INFO eval $(gpg-agent --daemon --pinentry-mode loopback) if [ ! -f "$GPG_KEY_PATH" ]; then echo "❌ $APP_NAME: ERROR: GPG secret key not found at '$GPG_KEY_PATH'" exit 1 fi echo "🔐 $APP_NAME: Importing GPG private key..." gpg --batch --import "$GPG_KEY_PATH" if [ -n "$GPG_PASSPHRASE_PATH" ] && [ -f "$GPG_PASSPHRASE_PATH" ]; then echo "🔑 $APP_NAME: Unlocking key to cache passphrase with GPG Agent..." KEY_FINGERPRINT=$(gpg --with-colons --import-options import-show --import < "$GPG_KEY_PATH" | awk -F: '/^sec:/ { print $5 }') if [ -z "$KEY_FINGERPRINT" ]; then echo "❌ $APP_NAME: Could not determine GPG key fingerprint from key file." exit 1 fi echo " - Unlocking key with fingerprint: $KEY_FINGERPRINT" echo "test" | gpg --quiet --batch --pinentry-mode loopback --passphrase-file "$GPG_PASSPHRASE_PATH" --sign -u "$KEY_FINGERPRINT" > /dev/null echo " - Key unlocked and passphrase cached successfully." fi # --- File Processing Loop --- echo "🔎 $APP_NAME: Processing all files in '$SOPS_INPUT_DIR'..." find "$SOPS_INPUT_DIR" -type f | while read -r source_file; do relative_path="${source_file#$SOPS_INPUT_DIR/}" destination_file="${SOPS_OUTPUT_DIR}/${relative_path}" mkdir -p "$(dirname "$destination_file")" SOPS_CMD="sops --decrypt" if [ "$SOPS_VERBOSE" = "true" ]; then SOPS_CMD="$SOPS_CMD --verbose" fi SOPS_CMD="$SOPS_CMD \"$source_file\" > \"$destination_file\"" if [ "$SOPS_VERBOSE" != "true" ]; then SOPS_CMD="$SOPS_CMD 2>/dev/null" fi if eval "$SOPS_CMD"; then echo " decrypted ✅ $relative_path" else echo " copied ↪️ $relative_path" cp "$source_file" "$destination_file" fi done echo "🎉 $APP_NAME: All files processed. Exiting."