#!/bin/bash

# omarchy:hidden=true
# omarchy:summary=Provide internal helpers for privileged Omarchy entrypoints

if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
  echo "omarchy-security-functions is an internal function library." >&2
  exit 64
fi

omarchy_security_require_privileged_bash_startup() {
  [[ $- == *p* ]] || return 1
  # The caller is this check's parent, under the number this /proc gives it.
  # arch-chroot runs the installer in a new PID namespace beneath the outer
  # /proc, where $$ names no process, or someone else's.
  /usr/bin/env -i /usr/bin/bash -p -c '
    stat=$(</proc/self/stat) || exit 1
    read -r _ caller _ <<<"${stat##*) }"
    mapfile -d "" -t argv <"/proc/$caller/cmdline" || exit 1
    executable=$(/usr/bin/readlink -e -- "/proc/$caller/exe") || exit 1
    [[ $executable == "/usr/bin/bash" &&
      ( ${argv[0]:-} == "/bin/bash" || ${argv[0]:-} == "/usr/bin/bash" ) &&
      ${argv[1]:-} == "-p" ]]
  ' omarchy-bash-startup
}

omarchy_security_sanitize_bash_environment() {
  local script=$1
  shift
  local entry name lastpipe_was_set=false
  local -a unsets=() statuses

  # Read the raw environment: privileged Bash ignores exported functions, but
  # leaves their records for ordinary child interpreters to import later.
  # lastpipe keeps the loop in this shell (job control is off in a script), so
  # env's status is PIPESTATUS: Bash can reap a process substitution before wait.
  [[ $- != *m* ]] || return 1
  shopt -q lastpipe && lastpipe_was_set=true
  shopt -s lastpipe
  /usr/bin/env -0 | while IFS= read -r -d '' entry; do
    name=${entry%%=*}
    case "$name" in
      BASH_ENV|ENV|SHELLOPTS|BASHOPTS|PS4|CDPATH|GLOBIGNORE|BASH_FUNC_*%%)
        unsets+=(-u "$name")
        ;;
    esac
  done
  statuses=("${PIPESTATUS[@]}")
  $lastpipe_was_set || shopt -u lastpipe
  (( statuses[0] == 0 )) || return 1
  if (( ${#unsets[@]} > 0 )); then
    exec /usr/bin/env "${unsets[@]}" /usr/bin/bash -p -- "$script" "$@"
  fi
}

omarchy_security_require_source_root() {
  local command_source command_name=${1##*/}
  command_source=$(/usr/bin/readlink -e -- "$1") || return 1

  # A runtime root selects the code used by this invocation. Accept the
  # canonical checkout containing the entrypoint or the package's bin links.
  if [[ ${OMARCHY_PATH:-} != /* || $(/usr/bin/realpath -e -- "$OMARCHY_PATH") != "$OMARCHY_PATH" ]] ||
    ! { [[ $command_source == "$OMARCHY_PATH/bin/$command_name" ]] ||
      [[ $OMARCHY_PATH == "/usr/share/omarchy" && $command_source == "/usr/bin/$command_name" ]]; }; then
    echo "OMARCHY_PATH does not match this Armbian command." >&2
    return 1
  fi
}

omarchy_security_install_signal_exit_traps() {
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM
}

omarchy_security_assert_root_directory() {
  local path=$1 expected_mode=$2 canonical owner actual_mode

  [[ $path == /* && -d $path && ! -L $path ]] || return 1
  canonical=$(/usr/bin/realpath -e -- "$path") || return 1
  [[ $canonical == "$path" ]] || return 1
  read -r owner actual_mode < <(/usr/bin/stat -Lc '%u %a' -- "$path") || return 1
  [[ $owner == "0" && $actual_mode == "$expected_mode" ]]
}

omarchy_security_prepare_private_root_directory() {
  local path=$1 parent=$2

  omarchy_security_assert_root_directory "$parent" 755 || return 1
  if [[ -e $path || -L $path ]]; then
    omarchy_security_assert_root_directory "$path" 700
  else
    /usr/bin/install -d -o root -g root -m 0700 -- "$path" || return 1
    omarchy_security_assert_root_directory "$path" 700
  fi
}
