#!/bin/bash

set -u

PENDING_PASSWORD_FILE="${TRIM_PKGVAR}/.pending-admin-password"

write_error() {
  message="$1"
  if [ -n "${TRIM_TEMP_LOGFILE:-}" ]; then
    printf '%s\n' "$message" > "$TRIM_TEMP_LOGFILE"
  fi
  printf '%s\n' "$message" >&2
}

password="${wizard_alist_password:-}"
confirm="${wizard_alist_password_confirm:-$password}"

# A missing value is allowed for unattended installs, in which case AList
# keeps its own randomly generated initial password.
if [ -z "$password" ]; then
  exit 0
fi

if [ "$password" != "$confirm" ]; then
  write_error "两次输入的 AList 管理员密码不一致。"
  exit 1
fi

password_length="${#password}"
if [ "$password_length" -lt 6 ] || [ "$password_length" -gt 128 ]; then
  write_error "AList 管理员密码长度必须为 6 到 128 个字符。"
  exit 1
fi

case "$password" in
  *$'\n'*|*$'\r'*)
    write_error "AList 管理员密码不能包含换行符。"
    exit 1
    ;;
esac

# Applying the password here can fail during installation because fnOS has not
# entered the service lifecycle yet. Stage it and let cmd/main apply it after
# the service is stopped and immediately before AList starts.
umask 077
if ! printf '%s' "$password" > "$PENDING_PASSWORD_FILE"; then
  write_error "无法保存 AList 管理员密码设置。"
  exit 1
fi
chmod 600 "$PENDING_PASSWORD_FILE" 2>/dev/null || true

exit 0
