#!/usr/bin/env sh
#
# ensure_infisical_profile <profile_env_file>
#
# Infisical's CLI keeps a single active login (~/.infisical/infisical-config.json)
# shared across every project on the machine. If you juggle multiple Infisical
# accounts (e.g. a client org vs. a personal org), running with-env in one repo
# can silently pull secrets while logged in as the wrong user.
#
# This switches the active `loggedInUserEmail` to the email configured in
# scripts/flags/infisical.env (INFISICAL_EMAIL=...) before infisical runs,
# provided that email is already logged in locally (`infisical login`).
# It is a no-op if the flag file is absent, only one user is logged in, or the
# expected user isn't logged in yet.
#
# POSIX sh, no bashisms: matches the rest of scripts/ which must stay
# busybox-compatible.

warn_infisical_profile() {
  echo "Warning: infisical-profile: $*" >&2
}

ensure_infisical_profile() {
  profile_env_file="${1:-}"

  if [ -z "$profile_env_file" ] || [ ! -f "$profile_env_file" ]; then
    return 0
  fi

  set -a
  # shellcheck source=/dev/null
  if ! . "$profile_env_file"; then
    set +a
    warn_infisical_profile "could not read $profile_env_file. Continuing with current Infisical profile."
    return 0
  fi
  set +a

  expected_email="${INFISICAL_EMAIL:-}"
  if [ -z "$expected_email" ]; then
    return 0
  fi

  config="${INFISICAL_CONFIG_PATH:-$HOME/.infisical/infisical-config.json}"
  lock="${INFISICAL_LOCK_PATH:-$HOME/.infisical/.switch.lock}"

  if [ ! -f "$config" ]; then
    warn_infisical_profile "Infisical config not found at $config. Continuing with current Infisical profile."
    return 0
  fi

  if ! command -v jq >/dev/null 2>&1; then
    warn_infisical_profile "jq is required to select Infisical profile. Continuing with current Infisical profile."
    return 0
  fi

  if ! command -v flock >/dev/null 2>&1; then
    warn_infisical_profile "flock is required to safely select Infisical profile. Continuing with current Infisical profile."
    return 0
  fi

  if ! mkdir -p "$(dirname "$lock")"; then
    warn_infisical_profile "could not create Infisical lock directory. Continuing with current Infisical profile."
    return 0
  fi

  (
    if ! flock 9; then
      warn_infisical_profile "could not lock Infisical profile config. Continuing with current Infisical profile."
      return 0
    fi

    user_count="$(jq -r '(.loggedInUsers // []) | length' "$config" 2>/dev/null)" || {
      warn_infisical_profile "could not parse Infisical config. Continuing with current Infisical profile."
      return 0
    }

    if [ "$user_count" -lt 2 ]; then
      return 0
    fi

    current_email="$(jq -r '.loggedInUserEmail // ""' "$config" 2>/dev/null)" || {
      warn_infisical_profile "could not read current Infisical profile. Continuing with current Infisical profile."
      return 0
    }

    if [ "$current_email" = "$expected_email" ]; then
      return 0
    fi

    domain="$(
      jq -er --arg email "$expected_email" \
        '.loggedInUsers[] | select(.email == $email) | .domain' \
        "$config" 2>/dev/null
    )" || {
      warn_infisical_profile "Infisical profile $expected_email is not logged in locally. Continuing with current Infisical profile."
      return 0
    }

    tmp="$(mktemp)" || {
      warn_infisical_profile "could not create temp file for Infisical profile switch. Continuing with current Infisical profile."
      return 0
    }

    if jq --arg email "$expected_email" --arg domain "$domain" \
      '.loggedInUserEmail = $email | .LoggedInUserDomain = $domain' \
      "$config" > "$tmp"; then
      chmod 600 "$tmp"
      mv "$tmp" "$config"
    else
      rm -f "$tmp"
      warn_infisical_profile "failed to update Infisical profile. Continuing with current Infisical profile."
    fi
  ) 9>"$lock"

  return 0
}
