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

read_service_property() {
  local service_name=$1
  local property_name=$2
  local systemctl_bin=${ENV_FILE_SYSTEMCTL_BIN:-systemctl}

  "$systemctl_bin" show --property="$property_name" --value "$service_name" \
    2>/dev/null || true
}

extract_env_file_argument() {
  local command_line=$1
  local value=

  if [[ $command_line =~ --env-file=([^[:space:]]+) ]]; then
    value=${BASH_REMATCH[1]}
  elif [[ $command_line =~ --env-file[[:space:]]+([^[:space:]]+) ]]; then
    value=${BASH_REMATCH[1]}
  fi

  value=${value#\"}
  value=${value%\"}
  value=${value%;}
  value=${value%\}}
  printf '%s\n' "$value"
}

resolve_env_file() {
  local service_name=${1:?service name is required}
  local requested_path=${2:-}
  local inherited_path=
  local service_working_directory=
  local invoking_home=
  local candidate=
  local filename=
  local directory=
  local existing=
  local -a search_directories=()
  local -a configured_directories=()

  if [[ -n $requested_path ]]; then
    if [[ ! -f $requested_path ]]; then
      echo "environment file not found: $requested_path" >&2
      return 1
    fi
    realpath "$requested_path"
    return
  fi

  inherited_path=$(extract_env_file_argument "$(read_service_property "$service_name" ExecStart)")
  if [[ -n $inherited_path ]]; then
    if [[ -f $inherited_path ]]; then
      realpath "$inherited_path"
      return
    fi
    echo "inherited environment file not found: $inherited_path; scanning fallbacks" >&2
  fi

  append_search_directory() {
    local path=${1:-}
    [[ -n $path && -d $path ]] || return 0
    path=$(realpath "$path")
    for existing in ${search_directories[@]+"${search_directories[@]}"}; do
      [[ $existing == "$path" ]] && return 0
    done
    search_directories+=("$path")
  }

  if [[ -n ${ENV_FILE_SEARCH_DIRS:-} ]]; then
    IFS=: read -r -a configured_directories <<<"$ENV_FILE_SEARCH_DIRS"
    for directory in ${configured_directories[@]+"${configured_directories[@]}"}; do
      append_search_directory "$directory"
    done
  else
    append_search_directory "$PWD"
    if [[ -n ${SUDO_USER:-} && ${SUDO_USER:-} != root ]] && command -v getent >/dev/null 2>&1; then
      invoking_home=$(getent passwd "$SUDO_USER" | cut -d: -f6 || true)
      append_search_directory "$invoking_home"
    fi
    service_working_directory=$(read_service_property "$service_name" WorkingDirectory)
    append_search_directory "$service_working_directory"
    append_search_directory "${HOME:-}"
    append_search_directory /root
  fi

  for filename in .env.prod .env.ext .env; do
    for directory in ${search_directories[@]+"${search_directories[@]}"}; do
      candidate="$directory/$filename"
      if [[ -f $candidate ]]; then
        realpath "$candidate"
        return
      fi
    done
  done

  echo "environment file not found; checked existing $service_name configuration and .env.prod, .env.ext, .env in: ${search_directories[*]-(no directories)}" >&2
  return 1
}

if [[ ${BASH_SOURCE[0]:-} == "$0" ]]; then
  if [[ $# -lt 1 || $# -gt 2 ]]; then
    echo "usage: $0 <service-name> [explicit-env-file]" >&2
    exit 2
  fi
  resolve_env_file "$@"
fi
