#!/usr/bin/env bash
# Reset the Growbud Edge Server administrator password (Linux).
#
#   sudo growbud-edge-reset-admin [--email ADDRESS]
#       Make a new one-time password. The next sign-in must change it.
#       The password goes into the note "Growbud Edge Server.txt" on the
#       desktop of this computer's user, and into ADMIN-CREDENTIALS.txt in
#       the install folder.
#   growbud-edge-reset-admin --gui
#       The same, from the "Reset Edge Server password" menu item. Asks for
#       an administrator password (pkexec) and shows the result.
#
# install.sh also runs it with these options:
#   --write-note [--force]   write the desktop note from ADMIN-CREDENTIALS.txt
#                            while the password is still the one-time one
#   --local-sign-in          make the key the Growbud app on this computer
#                            signs in with (~/.config/growbud/edge-local-signin.key)
#
# install.sh puts a copy in /usr/local/sbin with the install folder filled
# in below. GROWBUD_EDGE_DIR overrides it.
set -euo pipefail

EDGE_DIR="${GROWBUD_EDGE_DIR:-@EDGE_DIR@}"
case "$EDGE_DIR" in
    @*@) EDGE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ;;
esac
NOTE_NAME="Growbud Edge Server.txt"
KEY_RELPATH=".config/growbud/edge-local-signin.key"
DEFAULT_ADMIN_EMAIL="growbud@growbud.local"
LEGACY_ADMIN_EMAIL="admin@growbud.local"
INSTALLED_PATH=/usr/local/sbin/growbud-edge-reset-admin
TITLE="Reset Edge Server password"

# ── This computer's desktop user ─────────────────────────────────────────

passwd_entry() { getent passwd "$1" 2>/dev/null || true; }

# The user who sits at this computer: the one who ran sudo or pkexec, else
# the caller, else the first account (uid 1000) with a home folder.
note_user() {
    local name=""
    if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ]; then
        name="$SUDO_USER"
    elif [ -n "${PKEXEC_UID:-}" ] && [ "$PKEXEC_UID" != 0 ]; then
        name="$(passwd_entry "$PKEXEC_UID" | cut -d: -f1)"
    elif [ "$(id -u)" != 0 ]; then
        name="$(id -un)"
    else
        name="$(passwd_entry 1000 | cut -d: -f1)"
    fi
    [ -n "$name" ] && [ "$name" != root ] || return 1
    printf '%s' "$name"
}

user_home() {
    local home
    home="$(passwd_entry "$1" | cut -d: -f6)"
    [ -n "$home" ] && [ "$home" != / ] && [ -d "$home" ] || return 1
    printf '%s' "$home"
}

# The desktop folder (xdg-user-dirs, which knows a translated name), or
# nothing on a computer without a desktop.
desktop_dir() {
    local home dir=""
    home="$(user_home "$1")" || return 1
    if [ -f "$home/.config/user-dirs.dirs" ]; then
        dir="$(sed -n 's/^XDG_DESKTOP_DIR="\(.*\)"$/\1/p' "$home/.config/user-dirs.dirs" | tail -n 1)"
        dir="${dir/#\$HOME/$home}"
    fi
    [ -n "$dir" ] || dir="$home/Desktop"
    case "$dir" in
        "$home"|"$home/") return 1 ;;  # xdg sets the home folder when there is no desktop
        "$home"/*) ;;
        *) return 1 ;;
    esac
    [ -d "$dir" ] || return 1
    printf '%s' "$dir"
}

# as_user USER COMMAND...: run as the desktop user, so a file it writes is
# its own and a link it planted cannot redirect a root write.
as_user() {
    local user="$1"
    shift
    if [ "$(id -un)" = "$user" ]; then
        "$@"
    elif [ "$(id -u)" = 0 ] && command -v runuser >/dev/null 2>&1; then
        runuser -u "$user" -- "$@"
    elif [ "$(id -u)" = 0 ] && command -v sudo >/dev/null 2>&1; then
        sudo -n -u "$user" -- "$@"
    else
        return 1
    fi
}

# save_private DIR FILE: stdin to FILE (mode 0600), through a temp file in
# DIR and a rename. Runs as the desktop user.
# shellcheck disable=SC2016  # expanded by the inner sh
SAVE_PRIVATE='umask 077
tmp="$(mktemp "$1/.growbud-edge.XXXXXX")" || exit 1
if cat > "$tmp" && chmod 600 "$tmp" && mv -f "$tmp" "$2"; then exit 0; fi
rm -f "$tmp"
exit 1'

env_value() { sed -n "s/^$1=//p" "$EDGE_DIR/.env" 2>/dev/null | tail -n 1; }

# ── The desktop note ─────────────────────────────────────────────────────

note_text() { # USERNAME PASSWORD LAN_URL LOCAL_SIGN_IN
    printf 'Growbud Edge Server\n\n'
    printf 'Growbud app on this computer:  localhost\n'
    printf 'Other computers and phones:    the address in Settings > Edge Server
'
    printf 'Username:                      %s\n' "$1"
    printf 'Password:                      %s\n\n' "$2"
    printf 'Change the password in the app: Settings > Edge Server.\n'
    if [ "$4" = 1 ]; then
        printf 'The Growbud app on this computer signs in automatically.\n'
    fi
    printf '\n'
    printf 'If you forget the password, make a new one:\n'
    printf -- '- In the applications menu, select "%s".\n' "$TITLE"
    printf -- '- Or run this command: sudo growbud-edge-reset-admin\n\n'
    printf 'To update the Growbud app on this computer:\n'
    printf -- '- It updates itself when a new version is out. Restart it when it asks.\n'
    printf -- '- Or download the Linux package from https://growbud.io/download and run: sudo dpkg -i Growbud_*_amd64.deb\n\n'
    printf 'Keep this note private. Delete it after you set a new password.\n'
}

lan_url() {
    local host port
    host="$(env_value EDGE_HOSTNAME)"
    port="$(env_value HTTPS_PORT)"
    case "$host" in
        ""|localhost|127.*|::1) return 0 ;;
    esac
    printf 'https://%s:%s' "$host" "${port:-8443}"
}

# admin_must_change EMAIL: 0 while the administrator still has the one-time
# password, 1 after a change, 2 when the database does not answer.
admin_must_change() {
    local out
    out="$(cd "$EDGE_DIR" && docker compose exec -T -e PGPASSWORD="$(env_value POSTGRES_PASSWORD)" db \
        psql -U supabase_admin -h 127.0.0.1 -d postgres -X -tA -v email="$1" 2>/dev/null <<'SQL'
SELECT coalesce((raw_user_meta_data->>'must_change_password')::boolean, false)
  FROM auth.users WHERE lower(email) = lower(:'email') LIMIT 1;
SQL
)" || return 2
    case "$out" in
        t|true) return 0 ;;
        *) return 1 ;;
    esac
}

# write_note FORCE: 0 written, 1 nothing to write, 2 no desktop, 3 a note exists.
# Prints the note path on success. Never prints the password.
write_note() {
    local force="$1" creds="$EDGE_DIR/ADMIN-CREDENTIALS.txt" username password user dir note
    [ -r "$creds" ] || return 1
    username="$(sed -n 's/^Username: *//p' "$creds" | head -n 1)"
    password="$(sed -n 's/^Password: *//p' "$creds" | head -n 1)"
    [ -n "$username" ] && [ -n "$password" ] || return 1
    user="$(note_user)" || return 2
    dir="$(desktop_dir "$user")" || return 2
    note="$dir/$NOTE_NAME"
    if [ "$force" != 1 ] && { [ -e "$note" ] || [ -L "$note" ]; }; then
        return 3
    fi
    local local_sign_in=0
    [ -n "$(env_value LOCAL_SIGNIN_KEY_SHA256)" ] && local_sign_in=1
    note_text "$username" "$password" "$(lan_url)" "$local_sign_in" \
        | as_user "$user" sh -c "$SAVE_PRIVATE" sh "$dir" "$note" || return 2
    printf '%s' "$note"
}

admin_email() {
    local username
    username="$(sed -n 's/^Username: *//p' "$EDGE_DIR/ADMIN-CREDENTIALS.txt" 2>/dev/null | head -n 1)"
    case "$username" in
        *@*) printf '%s' "$username" ;;
        admin) printf '%s' "$LEGACY_ADMIN_EMAIL" ;;
        *) printf '%s' "$DEFAULT_ADMIN_EMAIL" ;;
    esac
}

# Exit status: 0 written or not needed, else as write_note. The note
# repeats ADMIN-CREDENTIALS.txt, which the first install and a reset
# write; since 2026-11-06 the first password is not flagged as temporary,
# so the note no longer waits for a must-change flag.
cmd_write_note() { # FORCE
    local note rc=0
    note="$(write_note "$1")" || rc=$?
    case "$rc" in
        0) echo "Wrote the sign-in note: $note" ;;
        1) echo "No one-time password in ADMIN-CREDENTIALS.txt. No desktop note." ;;
        2) echo "No desktop on this computer. No desktop note." ;;
        3) echo "A sign-in note is already on the desktop. It was not replaced." ;;
    esac
    return "$rc"
}

# ── Local sign-in key ────────────────────────────────────────────────────

set_env_value() { # KEY VALUE: replace or append, keeping the file and its mode.
    local tmp
    tmp="$(mktemp)"
    grep -v "^$1=" "$EDGE_DIR/.env" > "$tmp" || true
    printf '%s=%s\n' "$1" "$2" >> "$tmp"
    cat "$tmp" > "$EDGE_DIR/.env"
    rm -f "$tmp"
}

new_key() { head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n'; }

key_hash() { printf '%s' "$1" | sha256sum | cut -d' ' -f1; }

# The Growbud app on this computer signs in with this key. The Edge keeps
# only its SHA-256 (LOCAL_SIGNIN_KEY_SHA256 in .env); the key file is the
# desktop user's own, mode 0600. A key that still matches is kept.
cmd_local_sign_in() {
    local user home dir file key current want
    if ! user="$(note_user)" || ! home="$(user_home "$user")"; then
        echo "No desktop user on this computer. Local sign-in is off."
        return 0
    fi
    dir="$home/$(dirname "$KEY_RELPATH")"
    file="$home/$KEY_RELPATH"
    want="$(env_value LOCAL_SIGNIN_KEY_SHA256)"
    current="$(as_user "$user" cat "$file" 2>/dev/null | tr -d '[:space:]' || true)"
    if [ -n "$want" ] && [ -n "$current" ] && [ "$(key_hash "$current")" = "$want" ]; then
        echo "The Growbud app on this computer signs in as the administrator ($user)."
        return 0
    fi
    key="$(new_key)"
    [ "${#key}" = 43 ] || { echo "Could not make a local sign-in key." >&2; return 1; }
    if ! as_user "$user" mkdir -p "$dir" || ! as_user "$user" chmod 700 "$dir" \
        || ! printf '%s\n' "$key" | as_user "$user" sh -c "$SAVE_PRIVATE" sh "$dir" "$file"; then
        echo "Could not write $file. Local sign-in is off." >&2
        return 1
    fi
    set_env_value LOCAL_SIGNIN_KEY_SHA256 "$(key_hash "$key")"
    echo "The Growbud app on this computer signs in as the administrator ($user)."
}

# Turn local sign-in off: forget the hash and remove the key file.
cmd_no_local_sign_in() {
    local user home
    [ -f "$EDGE_DIR/.env" ] && set_env_value LOCAL_SIGNIN_KEY_SHA256 ""
    if user="$(note_user)" && home="$(user_home "$user")"; then
        as_user "$user" rm -f "$home/$KEY_RELPATH" || true
    fi
    echo "Local sign-in is off."
}

# ── Reset ────────────────────────────────────────────────────────────────

cmd_reset() { # EMAIL
    local email="$1" out note rc=0
    if [ "$(id -u)" != 0 ] && ! docker info >/dev/null 2>&1; then
        echo "Run this command with sudo: sudo growbud-edge-reset-admin" >&2
        return 1
    fi
    [ -f "$EDGE_DIR/docker-compose.yml" ] && [ -f "$EDGE_DIR/.env" ] \
        || { echo "The Edge Server is not installed in $EDGE_DIR." >&2; return 1; }
    # The init output holds the new password: keep it off the screen when
    # the note has it.
    if ! out="$(cd "$EDGE_DIR" && docker compose run --rm --no-deps -T \
        -e ADMIN_EMAIL="$email" \
        -e HOST_UID="$(stat -c %u "$EDGE_DIR/.env")" -e HOST_GID="$(stat -c %g "$EDGE_DIR/.env")" \
        init reset-admin 2>&1)"; then
        printf '%s\n' "$out" | grep -v -i 'password' >&2 || true
        echo "The password was not reset. Make sure that the Edge Server runs, then try again." >&2
        return 1
    fi
    note="$(write_note 1)" || rc=$?
    if [ "$rc" = 0 ]; then
        echo "The administrator has a new one-time password."
        echo "It is in the note \"$NOTE_NAME\" on your desktop."
        echo "You must set a new password at the next sign-in."
    else
        printf '%s\n' "$out" | sed -n '/New password for/,$p'
    fi
}

# ── Desktop menu item ────────────────────────────────────────────────────

show_result() { # OK MESSAGE
    if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
        if [ "$1" = 1 ]; then
            zenity --info --title="$TITLE" --no-wrap --text="$2" || true
        else
            zenity --error --title="$TITLE" --no-wrap --text="$2" || true
        fi
    elif [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v notify-send >/dev/null 2>&1; then
        notify-send --app-name=Growbud "$TITLE" "$2" || true
    else
        printf '%s\n' "$2"
    fi
}

cmd_gui() {
    local self out
    self="$(readlink -f "${BASH_SOURCE[0]}")"
    [ -x "$INSTALLED_PATH" ] && self="$INSTALLED_PATH"
    # No dialog program: run in a terminal so the person sees the result.
    if ! [ -t 1 ] && ! command -v zenity >/dev/null 2>&1 && ! command -v notify-send >/dev/null 2>&1 \
        && command -v x-terminal-emulator >/dev/null 2>&1; then
        # shellcheck disable=SC2016  # expanded by the inner bash
        exec x-terminal-emulator -e bash -c '"$1" --gui; read -r -p "Push Enter to close." _' bash "$self"
    fi
    if out="$(pkexec "$self" 2>&1)"; then
        show_result 1 "$out"
    else
        show_result 0 "${out:-The password was not reset.}"
        return 1
    fi
}

main() {
    local mode=reset force=0 email=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --gui) mode=gui; shift ;;
            --write-note) mode=note; shift ;;
            --force) force=1; shift ;;
            --local-sign-in) mode=local; shift ;;
            --no-local-sign-in) mode=nolocal; shift ;;
            --email) email="$2"; shift 2 ;;
            -h|--help) sed -n '2,21p' "${BASH_SOURCE[0]}"; return 0 ;;
            *) echo "Unknown option: $1" >&2; return 2 ;;
        esac
    done
    [ "$(uname -s)" = Linux ] || { echo "This command is for Linux." >&2; return 1; }
    case "$mode" in
        gui) cmd_gui ;;
        note) cmd_write_note "$force" ;;
        local) cmd_local_sign_in ;;
        nolocal) cmd_no_local_sign_in ;;
        reset) cmd_reset "${email:-$(admin_email)}" ;;
    esac
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    main "$@"
fi
