#!/usr/bin/env bash
set -euo pipefail

source ./scripts/Unix/starter.sh

env_file=".env"
if [ ! -f "$env_file" ]; then
  echo ".env file not found in the current directory." >&2
  exit 1
fi

# Read .env and export variables; collect for sorted output (portable: no associative arrays)
mapfile -t lines < <(sed -e 's/^\s*//;s/\s*$//' "$env_file" | awk 'NF && $0 !~ /^#/ && $0 ~ /=/')

kv_list=()
for raw in "${lines[@]}"; do
  key=${raw%%=*}
  value=${raw#*=}
  # Trim whitespace around key and value
  key=$(echo "$key" | sed -e 's/^\s*//' -e 's/\s*$//')
  value=$(echo "$value" | sed -e 's/^\s*//' -e 's/\s*$//')
  # Strip matching quotes
  if [ -n "$value" ] && [ "${value:0:1}" = '"' ] && [ "${value: -1}" = '"' ]; then
    value=${value:1:${#value}-2}
  elif [ -n "$value" ] && [ "${value:0:1}" = "'" ] && [ "${value: -1}" = "'" ]; then
    value=${value:1:${#value}-2}
  fi
  export "$key=$value"
  kv_list+=("$key=$value")
done

if [ ${#kv_list[@]} -gt 0 ]; then
  printf "%s\n" "${kv_list[@]}" | sort | tr "\n" ";" | sed 's/;$/\n/'
fi
