#!/bin/bash

# omarchy:summary=Enable or disable passwordless boot and wake from sleep
# omarchy:args=[1|3|always|--active|--disable]
# omarchy:requires-sudo=true

# Passphrases live in variables; never trace them.
set +x
set -euo pipefail

SCRIPT_SELF=$(readlink -e -- "${BASH_SOURCE[0]}")
SCRIPT_DIR=${SCRIPT_SELF%/*}

# Allow redirecting system paths in non-root unit tests only. When running as
# real root, all paths stay anchored at the real filesystem root.
TEST_ROOT=""
if (( EUID != 0 )) && [[ -n ${OMARCHY_PASSWORDLESS_LOGIN_TEST_ROOT:-} ]]; then
  TEST_ROOT=${OMARCHY_PASSWORDLESS_LOGIN_TEST_ROOT%/}
fi

readonly KEYFILE="${TEST_ROOT}/crypto_keyfile.bin"
readonly MKINITCPIO_DROPIN="${TEST_ROOT}/etc/mkinitcpio.conf.d/99-omarchy-passwordless-login.conf"
readonly STATE_DIR="${TEST_ROOT}/var/lib/omarchy"
readonly STATE_FILE="${STATE_DIR}/passwordless-login"
readonly SYSTEMD_DIR="${TEST_ROOT}/etc/systemd/system"
readonly EXPIRE_UNIT_NAME="omarchy-passwordless-login-expire.service"
readonly EXPIRE_UNIT="${SYSTEMD_DIR}/${EXPIRE_UNIT_NAME}"
readonly EXPIRE_WANT="${SYSTEMD_DIR}/multi-user.target.wants/${EXPIRE_UNIT_NAME}"
readonly LOCK_FILE="${TEST_ROOT}/run/lock/omarchy-passwordless-login.lock"
readonly CMDLINE_GROUP="omarchy-passwordless-login"
readonly PROC_CMDLINE="${TEST_ROOT:+${TEST_ROOT}/proc/cmdline}"

usage() {
  echo "Usage: omarchy-setup-security-passwordless-login [1|3|always|--active|--disable]" >&2
  exit 2
}

valid_mode() {
  case "$1" in
    1|3|always) return 0 ;;
    *) return 1 ;;
  esac
}

setup_root_path() {
  if [[ -z $TEST_ROOT ]]; then
    export PATH="$SCRIPT_DIR:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
  else
    export PATH="$PATH:$SCRIPT_DIR"
  fi
}

with_lock() (
  local lock_dir=${LOCK_FILE%/*}
  mkdir -p "$lock_dir"
  exec 9>"$LOCK_FILE"
  flock 9
  "$@"
)

# The LUKS partition beneath /, or nothing when / is not encrypted. Fails when
# it cannot tell, including a crypt layer whose LUKS partition lsblk cannot name.
root_luks_device() {
  local root_source ancestry device
  root_source=$(findmnt -no SOURCE /) && [[ -n $root_source ]] || return 1
  ancestry=$(lsblk -nsrpo NAME,TYPE,FSTYPE "${root_source%%[*}") || return 1
  device=$(awk '$3 == "crypto_LUKS" { print $1; exit }' <<<"$ancestry")
  if [[ -n $device ]]; then
    readlink -f "$device"
  elif awk '$2 == "crypt" { found = 1 } END { exit !found }' <<<"$ancestry"; then
    return 1
  fi
}

detect_initramfs_hook() {
  local cmdline_path=${PROC_CMDLINE:-/proc/cmdline}
  local cmdline=""
  [[ -r $cmdline_path ]] && cmdline=$(<"$cmdline_path")

  if [[ " $cmdline " == *" rd.luks."* ]]; then
    echo "sd-encrypt"
  elif [[ " $cmdline " == *" cryptdevice="* ]]; then
    echo "encrypt"
  elif grep -Eq '\bsd-encrypt\b' "${TEST_ROOT}/etc/mkinitcpio.conf" "${TEST_ROOT}/etc/mkinitcpio.conf.d/"*.conf 2>/dev/null; then
    echo "sd-encrypt"
  else
    echo "encrypt"
  fi
}

# Print the enabled key slots on a LUKS device, one per line.
luks_enabled_slots() {
  local dev=$1 dump
  dump=$(cryptsetup luksDump "$dev") || return 1
  awk '
    /^[^ \t]/ { keyslots = ($0 == "Keyslots:") }
    keyslots && /^ +[0-9]+: luks2/ { sub(":", "", $1); print $1 }
    /^Key Slot [0-9]+: ENABLED/ { sub(":", "", $3); print $3 }
  ' <<<"$dump"
}

# Print the key slot that KEYFILE opens. Returns 2 if it opens none.
keyfile_slot() {
  local dev=$1 keyfile=$2 out status=0
  out=$(LC_ALL=C cryptsetup open --test-passphrase --verbose --token-type passphrase-only --key-file "$keyfile" "$dev" 2>&1) || status=$?
  (( status == 0 )) || return "$status"
  grep -o 'Key slot [0-9]* unlocked' <<<"$out" | grep -o '[0-9]*' | head -1
}

STATE_MODE=""
STATE_REMAINING=""
STATE_UUID=""
STATE_SLOT=""
STATE_HOOK=""

read_state() {
  STATE_MODE=""
  STATE_REMAINING=""
  STATE_UUID=""
  STATE_SLOT=""
  STATE_HOOK=""

  [[ -f $STATE_FILE && ! -L $STATE_FILE ]] || return 1
  if [[ -z $TEST_ROOT ]]; then
    local owner
    owner=$(stat -Lc '%u' -- "$STATE_FILE" 2>/dev/null) || return 1
    [[ $owner == "0" ]] || return 1
  fi

  local key value
  while IFS='=' read -r key value; do
    case "$key" in
      MODE) STATE_MODE=$value ;;
      REMAINING) STATE_REMAINING=$value ;;
      DEVICE_UUID) STATE_UUID=$value ;;
      KEY_SLOT) STATE_SLOT=$value ;;
      INITRAMFS_HOOK) STATE_HOOK=$value ;;
    esac
  done <"$STATE_FILE"

  case "$STATE_MODE" in
    always) return 0 ;;
    count) [[ $STATE_REMAINING =~ ^[0-9]+$ ]] && return 0 ;;
  esac
  return 1
}

write_atomic_file() {
  local dest=$1 mode=$2 content=$3
  local dir=${dest%/*} stage
  mkdir -p "$dir"
  stage=$(mktemp "${dir}/.${dest##*/}.new.XXXXXX")
  printf '%s' "$content" >"$stage"
  chmod "$mode" "$stage"
  [[ -n $TEST_ROOT ]] || chown root:root "$stage"
  mv -Tf -- "$stage" "$dest"
}

write_state() {
  local mode=$1 remaining=$2 uuid=$3 slot=$4 hook=$5
  local body
  body=$(printf 'MODE=%s\nREMAINING=%s\nDEVICE_UUID=%s\nKEY_SLOT=%s\nINITRAMFS_HOOK=%s\n' \
    "$mode" "$remaining" "$uuid" "$slot" "$hook")
  write_atomic_file "$STATE_FILE" 0644 "$body"
}

install_mkinitcpio_dropin() {
  local body
  body=$(cat <<'EOF'
# Managed by omarchy-setup-security-passwordless-login.
if [[ -f /crypto_keyfile.bin && ! -L /crypto_keyfile.bin ]]; then
  FILES+=(/crypto_keyfile.bin)
fi
EOF
)
  write_atomic_file "$MKINITCPIO_DROPIN" 0644 "${body}"$'\n'
}

install_expire_service() {
  local body
  body=$(cat <<'EOF'
[Unit]
Description=Decrement or revoke Omarchy passwordless login boot grant
After=local-fs.target
ConditionPathExists=/var/lib/omarchy/passwordless-login

[Service]
Type=oneshot
ExecStart=/usr/bin/bash -c 'omarchy_path=/usr/share/omarchy; if [[ -f /etc/omarchy.conf && ! -L /etc/omarchy.conf && $(stat -c %%u /etc/omarchy.conf) == 0 ]]; then source /etc/omarchy.conf; fi; if [[ -x "${OMARCHY_PATH:-}/bin/omarchy-setup-security-passwordless-login" ]]; then exec "$OMARCHY_PATH/bin/omarchy-setup-security-passwordless-login" __boot-tick; elif [[ -x "$omarchy_path/bin/omarchy-setup-security-passwordless-login" ]]; then exec "$omarchy_path/bin/omarchy-setup-security-passwordless-login" __boot-tick; else exec /usr/bin/omarchy-setup-security-passwordless-login __boot-tick; fi'

[Install]
WantedBy=multi-user.target
EOF
)
  write_atomic_file "$EXPIRE_UNIT" 0644 "${body}"$'\n'
  mkdir -p "${EXPIRE_WANT%/*}"
  ln -sf "../${EXPIRE_UNIT_NAME}" "$EXPIRE_WANT"
  if [[ -z $TEST_ROOT ]]; then
    systemctl daemon-reload >/dev/null 2>&1 || true
  fi
}

remove_expire_service() {
  rm -f -- "$EXPIRE_WANT" "$EXPIRE_UNIT"
  if [[ -z $TEST_ROOT ]]; then
    systemctl daemon-reload >/dev/null 2>&1 || true
  fi
}

create_keyfile() {
  local dir=${KEYFILE%/*} stage
  [[ -n $dir ]] || dir="/"
  stage=$(mktemp "${dir}/.crypto_keyfile.bin.new.XXXXXX")
  chmod 0600 "$stage"
  dd if=/dev/urandom of="$stage" bs=64 count=1 status=none
  if [[ -z $TEST_ROOT ]]; then
    chown root:root "$stage"
    chmod 0000 "$stage"
  fi
  mv -Tf -- "$stage" "$KEYFILE"
}

revoke_keyfile_slot() {
  local dev=$1
  [[ -f $KEYFILE && ! -L $KEYFILE ]] || return 0
  [[ -n $dev ]] || return 0

  local slot status=0
  slot=$(keyfile_slot "$dev" "$KEYFILE") || status=$?
  if (( status == 2 )); then
    # Keyfile does not open any slot (already revoked manually).
    return 0
  elif (( status != 0 )); then
    echo "Could not verify the passwordless login key slot on $dev." >&2
    return 1
  fi

  local -a slots=()
  mapfile -t slots < <(luks_enabled_slots "$dev")
  if (( ${#slots[@]} < 2 )); then
    echo "Refusing to remove the only remaining LUKS key slot on $dev." >&2
    return 1
  fi

  cryptsetup luksRemoveKey -q "$dev" "$KEYFILE"
}

slot_is_enabled() {
  local dev=$1 target=$2 slots s
  [[ -n $dev ]] || return 2
  slots=$(luks_enabled_slots "$dev") || return 2
  while IFS= read -r s; do
    [[ $s == "$target" ]] && return 0
  done <<<"$slots"
  return 1
}

disable_locked() {
  setup_root_path
  local dev="" had_state=0

  if read_state; then
    had_state=1
  fi

  dev=$(root_luks_device 2>/dev/null || true)
  if [[ -z $dev && -n $STATE_UUID && -e "${TEST_ROOT}/dev/disk/by-uuid/${STATE_UUID}" ]]; then
    dev=$(readlink -f "${TEST_ROOT}/dev/disk/by-uuid/${STATE_UUID}")
  fi

  if (( had_state == 0 )) && [[ ! -e $MKINITCPIO_DROPIN && ! -e $EXPIRE_UNIT ]]; then
    return 0
  fi

  # Revoke the LUKS key slot first so even an interrupted boot-image rebuild
  # cannot leave the embedded initramfs key accepted by the disk. Never clear
  # state if the enrolled slot cannot be confirmed revoked (e.g. if the
  # keyfile was deleted or replaced while copies remain in boot images).
  if [[ -f $KEYFILE && ! -L $KEYFILE ]]; then
    revoke_keyfile_slot "$dev" || return 1
    if [[ -n $STATE_SLOT ]]; then
      local slot_status=0
      slot_is_enabled "$dev" "$STATE_SLOT" || slot_status=$?
      if (( slot_status != 1 )); then
        echo "LUKS key slot $STATE_SLOT on ${dev:-root device} is still enabled (or could not be verified) because $KEYFILE did not match it." >&2
        echo "Revoke it manually with: sudo cryptsetup luksKillSlot ${dev:-<luks-device>} $STATE_SLOT" >&2
        echo "Then run: omarchy-setup-security-passwordless-login --disable" >&2
        return 1
      fi
    fi
    rm -f -- "$KEYFILE"
  elif [[ -n $STATE_SLOT ]]; then
    local slot_status=0
    slot_is_enabled "$dev" "$STATE_SLOT" || slot_status=$?
    if (( slot_status != 1 )); then
      echo "Cannot revoke LUKS key slot $STATE_SLOT on ${dev:-root device} because $KEYFILE is missing; copies in boot images or elsewhere could still unlock the disk." >&2
      echo "Revoke it manually with: sudo cryptsetup luksKillSlot ${dev:-<luks-device>} $STATE_SLOT" >&2
      echo "Then run: omarchy-setup-security-passwordless-login --disable" >&2
      return 1
    fi
  fi

  rm -f -- "$MKINITCPIO_DROPIN" "$STATE_FILE"
  remove_expire_service

  omarchy-boot-cmdline unset "$CMDLINE_GROUP" || return 1
  omarchy-boot-rebuild || return 1
}

enable_locked() (
  local target=$1
  setup_root_path

  local mode remaining
  if [[ $target == "always" ]]; then
    mode="always"
    remaining="0"
  else
    mode="count"
    remaining=$target
  fi

  local dev uuid hook
  dev=$(root_luks_device) || {
    echo "Could not determine the root LUKS device." >&2
    return 1
  }
  if [[ -z $dev ]]; then
    echo "Your root drive is not encrypted with LUKS. Passwordless login only applies to encrypted disks." >&2
    return 1
  fi

  uuid=$(lsblk -dno UUID "$dev") && [[ -n $uuid ]] || {
    echo "Could not read the UUID of $dev." >&2
    return 1
  }
  hook=$(detect_initramfs_hook)

  # If already active with a valid enrolled keyfile, updating the boot count or
  # switching between timed and Always only requires updating state and unit.
  if read_state && [[ -f $KEYFILE && ! -L $KEYFILE && -f $MKINITCPIO_DROPIN ]]; then
    local existing_slot=""
    if existing_slot=$(keyfile_slot "$dev" "$KEYFILE"); then
      write_state "$mode" "$remaining" "$uuid" "$existing_slot" "$hook"
      if [[ $mode == "count" ]]; then
        install_expire_service
      else
        remove_expire_service
      fi
      return 0
    fi
  fi

  local backends
  if ! backends=$(omarchy-boot-backend --managed) || [[ -z $backends || $backends == "none" ]]; then
    echo "Passwordless login requires a boot loader whose boot images Armbian manages." >&2
    return 1
  fi

  if [[ -L $KEYFILE || ( -e $KEYFILE && ! -f $KEYFILE ) ]]; then
    echo "Refusing to use $KEYFILE because it is not a regular file." >&2
    return 1
  fi
  if [[ -e $KEYFILE ]] && ! read_state; then
    echo "$KEYFILE already exists and is not managed by Armbian. Remove it first if you want Armbian to manage passwordless login." >&2
    return 1
  fi

  local -a existing_slots=()
  mapfile -t existing_slots < <(luks_enabled_slots "$dev")
  if (( ${#existing_slots[@]} < 1 )); then
    echo "Could not read enabled LUKS key slots on $dev." >&2
    return 1
  fi

  local passphrase=""
  if [[ ! -t 0 ]]; then
    IFS= read -r -d '' passphrase || true
  fi

  local key_added=0 dropin_written=0 cmdline_written=0 state_written=0 unit_written=0 keyfile_created=0
  rollback_enable() {
    local rc=$?
    trap - EXIT HUP INT TERM
    if (( rc != 0 )); then
      echo "Rolling back passwordless login changes..." >&2
      if (( key_added )); then
        revoke_keyfile_slot "$dev" >/dev/null 2>&1 || true
      fi
      if (( keyfile_created )); then
        rm -f -- "$KEYFILE"
      fi
      if (( dropin_written )); then
        rm -f -- "$MKINITCPIO_DROPIN"
      fi
      if (( cmdline_written )); then
        omarchy-boot-cmdline unset "$CMDLINE_GROUP" >/dev/null 2>&1 || true
      fi
      if (( unit_written )); then
        remove_expire_service
      fi
      if (( state_written )); then
        rm -f -- "$STATE_FILE"
      fi
    fi
    exit "$rc"
  }
  trap rollback_enable EXIT
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM

  create_keyfile || return 1
  keyfile_created=1

  if [[ -n $passphrase ]]; then
    printf '%s' "$passphrase" | cryptsetup luksAddKey --iter-time 10 --key-file - "$dev" "$KEYFILE" || return 1
  else
    echo "Enter your current disk encryption password to enroll the boot unlock key..."
    cryptsetup luksAddKey --iter-time 10 "$dev" "$KEYFILE" || return 1
  fi
  key_added=1

  local slot
  slot=$(keyfile_slot "$dev" "$KEYFILE") || {
    echo "The enrolled boot key could not unlock $dev." >&2
    return 1
  }

  install_mkinitcpio_dropin || return 1
  dropin_written=1

  if [[ $hook == "sd-encrypt" ]]; then
    omarchy-boot-cmdline set "$CMDLINE_GROUP" "rd.luks.key=${uuid}=/crypto_keyfile.bin" || return 1
    cmdline_written=1
  fi

  write_state "$mode" "$remaining" "$uuid" "$slot" "$hook" || return 1
  state_written=1

  if [[ $mode == "count" ]]; then
    install_expire_service || return 1
    unit_written=1
  else
    remove_expire_service
  fi

  echo "Rebuilding boot images..."
  omarchy-boot-rebuild || return 1

  trap - EXIT HUP INT TERM
)

boot_tick_locked() {
  setup_root_path
  read_state || {
    remove_expire_service
    return 0
  }

  if [[ $STATE_MODE == "always" ]]; then
    remove_expire_service
    return 0
  fi

  local next=$((10#$STATE_REMAINING - 1))
  if (( next > 0 )); then
    write_state "count" "$next" "$STATE_UUID" "$STATE_SLOT" "$STATE_HOOK"
    return 0
  fi

  # The final allowed boot has started: revoke immediately so the next boot
  # requires the disk encryption password again.
  disable_locked
}

format_status() {
  if [[ $STATE_MODE == "always" ]]; then
    echo "Always"
  elif (( 10#$STATE_REMAINING == 1 )); then
    echo "Next boot"
  else
    echo "Next ${STATE_REMAINING} boots"
  fi
}

show_enabled_summary() {
  case "$1" in
    1) echo "Passwordless login has been ENABLED for the next boot. Your password will be required again after that." ;;
    3) echo "Passwordless login has been ENABLED for the next 3 boots. Your password will be required again after that." ;;
    always) echo "Passwordless login has been ENABLED permanently. Run Setup > Security > Passwordless Login again to disable it." ;;
  esac
}

run_privileged() {
  if [[ -n $TEST_ROOT ]]; then
    sudo "$SCRIPT_SELF" "$@"
  else
    sudo omarchy-setup-security-passwordless-login "$@"
  fi
}

ensure_sudo() {
  if [[ -z $TEST_ROOT ]]; then
    sudo -v
  fi
}

refresh_indicator() {
  omarchy-shell -q omarchy.indicators refresh >/dev/null 2>&1 || true
}

run_with_spinner() {
  local title=$1
  shift
  local log status=0 pid
  log=$(mktemp)
  "$@" >"$log" 2>&1 &
  pid=$!
  if [[ -t 1 ]]; then
    gum spin --spinner dot --title "$title" -- bash -c 'while kill -0 "$1" 2>/dev/null; do sleep 0.1; done' _ "$pid" </dev/null || true
  else
    echo "$title"
  fi
  wait "$pid" || status=$?
  if (( status != 0 )) && [[ -s $log ]]; then
    cat "$log" >&2
  fi
  rm -f "$log"
  return "$status"
}

# Internal privileged entrypoints (invoked via sudo or systemd boot unit).
case "${1:-}" in
  __enable)
    (($# == 2)) && valid_mode "$2" || usage
    if [[ -z $TEST_ROOT ]] && (( EUID != 0 )); then
      echo "omarchy-setup-security-passwordless-login: __enable requires root." >&2
      exit 1
    fi
    with_lock enable_locked "$2"
    exit
    ;;
  __disable)
    (($# == 1)) || usage
    if [[ -z $TEST_ROOT ]] && (( EUID != 0 )); then
      echo "omarchy-setup-security-passwordless-login: __disable requires root." >&2
      exit 1
    fi
    with_lock disable_locked
    exit
    ;;
  __boot-tick)
    (($# == 1)) || usage
    if [[ -z $TEST_ROOT ]] && (( EUID != 0 )); then
      echo "omarchy-setup-security-passwordless-login: __boot-tick requires root." >&2
      exit 1
    fi
    with_lock boot_tick_locked
    exit
    ;;
esac

if [[ ${1:-} == "--active" ]]; then
  (($# == 1)) || usage
  read_state && [[ -f $MKINITCPIO_DROPIN ]]
  exit
fi

if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
  echo "Usage: omarchy-setup-security-passwordless-login [1|3|always|--active|--disable]"
  echo ""
  echo "Enables or disables automatic LUKS disk unlock at boot and passwordless wake from sleep."
  echo "Options: 1 (Next boot), 3 (Next 3 boots), always (Always), --active, --disable."
  exit 0
fi

(($# <= 1)) || usage
arg=${1:-}
if (($# == 1)) && [[ $arg != "--disable" ]] && ! valid_mode "$arg"; then
  usage
fi

# Check current state before taking action.
active=0
if read_state && [[ -f $MKINITCPIO_DROPIN ]]; then
  active=1
fi

if [[ $arg == "--disable" ]]; then
  if (( active == 0 )) && [[ ! -e $MKINITCPIO_DROPIN && ! -e $EXPIRE_UNIT ]]; then
    refresh_indicator
    echo "Passwordless login is already DISABLED."
    exit 0
  fi
  echo "Disabling passwordless login..."
  echo ""
  ensure_sudo
  status=0
  run_with_spinner "Disabling passwordless login and rebuilding boot images (this can take a moment)..." run_privileged __disable || status=$?
  refresh_indicator
  (( status == 0 )) || exit "$status"
  echo ""
  echo "Passwordless login has been DISABLED. Your password will be required on boot and wake from sleep."
  exit 0
fi

if (( active == 1 )) && [[ -z $arg ]]; then
  echo "Passwordless login is currently ENABLED ($(format_status))."
  echo "Disabling passwordless login..."
  echo ""
  ensure_sudo
  status=0
  run_with_spinner "Disabling passwordless login and rebuilding boot images (this can take a moment)..." run_privileged __disable || status=$?
  refresh_indicator
  (( status == 0 )) || exit "$status"
  echo ""
  echo "Passwordless login has been DISABLED. Your password will be required on boot and wake from sleep."
  exit 0
fi

# Enabling (or changing duration while already enabled): verify LUKS root first.
root_dev=$(root_luks_device) || {
  echo "Could not determine the root drive encryption state." >&2
  exit 1
}
if [[ -z $root_dev ]]; then
  echo "Your root drive is not encrypted with LUKS. Passwordless login only applies to encrypted disks." >&2
  exit 1
fi

mode=$arg
if [[ -z $mode ]]; then
  choice=$(gum choose --header "How long should passwordless login stay enabled?" "Next boot" "Next 3 boots" "Always") || exit 130
  case "$choice" in
    "Next boot") mode=1 ;;
    "Next 3 boots") mode=3 ;;
    "Always") mode=always ;;
    *) exit 130 ;;
  esac
fi

case "$mode" in
  1) duration="for the next boot" ;;
  3) duration="for the next 3 boots" ;;
  always) duration="always" ;;
esac

echo ""
echo "⚠️  WARNING: This places an unencrypted LUKS unlock key inside your boot"
echo "image so this machine boots straight to your desktop without asking for"
echo "your disk encryption password ($duration), and skips locking the screen"
echo "on sleep so waking from sleep is also passwordless."
echo ""
echo "Anyone with physical access to this machine (or its boot partition) can"
echo "boot into your system and read your disk while this is enabled."
echo ""
case "$mode" in
  1)
    echo "Passwordless login will automatically revoke itself on the next boot,"
    echo "so the boot after that will require your password again."
    ;;
  3)
    echo "Passwordless login will automatically revoke itself after 3 boots,"
    echo "so the 4th boot will require your password again."
    ;;
  always)
    echo "Passwordless login will remain enabled across all reboots until you disable it."
    ;;
esac
echo "Run Setup > Security > Passwordless Login again to disable it at any time."
echo ""

if gum confirm "Enable passwordless login ($duration)? This weakens disk encryption!"; then
  ensure_sudo
  passphrase=""
  if (( active == 0 )); then
    passphrase=$(gum input --password --header "Enter your disk encryption password") || exit 130
    if [[ -z $passphrase ]]; then
      echo "Password cannot be empty." >&2
      exit 1
    fi
    spin_title="Enabling passwordless login and rebuilding boot images (this can take a moment)..."
  else
    spin_title="Updating passwordless login..."
  fi
  run_enable_with_passphrase() {
    if [[ -n $passphrase ]]; then
      printf '%s' "$passphrase" | run_privileged __enable "$mode"
    else
      run_privileged __enable "$mode" </dev/null
    fi
  }
  status=0
  run_with_spinner "$spin_title" run_enable_with_passphrase || status=$?
  refresh_indicator
  (( status == 0 )) || exit "$status"
  echo ""
  show_enabled_summary "$mode"
else
  echo "Aborted. No changes made."
fi
