#!/usr/bin/env bash
# This script generates config.env and secrets.env files for an app
# by evaluating variables in the app's .env file and splitting them
# into regular config and secret variables based on the "# Secrets" marker
#
# Usage: bin/generate-config [app-name]

set -e

# Source environment variables from load-env.sh
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"
if [ -f "$REPO_DIR/load-env.sh" ]; then
  source "$REPO_DIR/load-env.sh"
fi

# Function to process a single app
process_app() {
  local APP_NAME="$1"
  local APP_DIR="$APPS_DIR/$APP_NAME"
  local ENV_FILE="$APP_DIR/config/.env"
  local CONFIG_FILE="$APP_DIR/config/config.env"
  local SECRETS_FILE="$APP_DIR/config/secrets.env"

  # Check if the app exists
  if [ ! -d "$APP_DIR" ]; then
    echo "Error: App '$APP_NAME' not found"
    return 1
  fi

  # Check if the .env file exists
  if [ ! -f "$ENV_FILE" ]; then
    echo "Warning: Environment file not found: $ENV_FILE"
    return 0
  fi

  # Process the .env file
  echo "Generating config files for $APP_NAME..."

  # Create temporary files for processed content
  local TMP_FILE="$APP_DIR/config/processed.env"

  # Process the file with envsubst to expand variables
  envsubst < "$ENV_FILE" > $TMP_FILE

  # Initialize header for output files
  echo "# Generated by \`generate-config\` on $(date)" > "$CONFIG_FILE"
  echo "# Generated by \`generate-config\` on $(date)" > "$SECRETS_FILE"

  # Find the line number of the "# Secrets" marker
  local SECRETS_LINE=$(grep -n "^# Secrets" $TMP_FILE | cut -d':' -f1)

  if [ -n "$SECRETS_LINE" ]; then
    # Extract non-comment lines with "=" before the "# Secrets" marker
    head -n $((SECRETS_LINE - 1)) $TMP_FILE | grep -v "^#" | grep "=" >> "$CONFIG_FILE"  
    
    # Extract non-comment lines with "=" after the "# Secrets" marker
    tail -n +$((SECRETS_LINE + 1)) $TMP_FILE | grep -v "^#" | grep "=" >> "$SECRETS_FILE"
  else
    # No secrets marker found, put everything in config
    grep -v "^#" $TMP_FILE | grep "=" >> "$CONFIG_FILE"
  fi

  # Clean up
  rm -f "$TMP_FILE"

  echo "Generated:"
  echo "  - $CONFIG_FILE"
  echo "  - $SECRETS_FILE"
}

# Process all apps or specific app
if [ $# -lt 1 ]; then
  # No app name provided - process all apps
  for app_dir in "$APPS_DIR"/*; do
    if [ -d "$app_dir" ]; then
      APP_NAME="$(basename "$app_dir")"
      process_app "$APP_NAME"
    fi
  done
  exit 0
fi

APP_NAME="$1"
process_app "$APP_NAME"