#!/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

declare -A env_vars
while IFS= read -r line; do
  line="${line#"${line%%[![:space:]]*}"}"
  line="${line%"${line##*[![:space:]]}"}"
  if [ -z "$line" ] || [[ "$line" == \#* ]] || [[ "$line" != *=* ]]; then
    continue
  fi
  key="${line%%=*}"
  value="${line#*=}"
  if [[ ( "$value" == \"*\" && "$value" == *\" ) || ( "$value" == \'*\' && "$value" == *\' ) ]]; then
    value="${value:1:-1}"
  fi
  export "$key=$value"
  env_vars["$key"]="$value"
done < "$env_file"

if [ "${#env_vars[@]}" -gt 0 ]; then
  IFS=$'\n' sorted=($(for k in "${!env_vars[@]}"; do echo "${k}=${env_vars[$k]}"; done | sort))
  printf "%s" "${sorted[0]}"
  for entry in "${sorted[@]:1}"; do
    printf ";%s" "$entry"
  done
  echo
fi
