#!/bin/sh
# debconf question script. Runs before unpacking, and again on
# `dpkg-reconfigure jray-server`.
#
# Existing values are read back out of /etc/jray-server/env first, so a
# reconfigure shows what is actually in force rather than the package defaults.
# Without this, an operator who edited the env file by hand would be shown stale
# answers and silently have their edits reverted by postinst.
set -e
. /usr/share/debconf/confmodule

ENV_FILE=/etc/jray-server/env

# Read one KEY=value out of the env file, ignoring comments. Values are written
# unquoted by postinst, so no unquoting is needed.
env_value() {
    [ -f "$ENV_FILE" ] || return 0
    sed -n "s/^$1=//p" "$ENV_FILE" | tail -1
}

# Seed only a question debconf has never had an answer to.
#
# The test is the `seen` flag, not whether the value is empty: two of these
# templates carry a Default, so db_get returns "localhost" or "127.0.0.1:8080"
# for a question nobody has answered, and an emptiness check would never seed
# them. `seen` distinguishes "this is the template default" from "somebody chose
# this", which is the actual question.
#
# And it has to be a guard rather than an unconditional db_set. debconf-set-
# selections marks what it sets as seen, so an unconditional seed would overwrite
# a value the operator had just preseeded — every unattended install would
# quietly reconfigure itself back to whatever was already on disk. Preseeding is
# the entire point of the unattended path, so debconf wins wherever it has an
# answer and the env file only fills in what it does not.
seed() {  # seed <debconf-key> <env-key>
    db_fget "$1" seen || RET=""
    [ "$RET" = "true" ] && return 0
    v=$(env_value "$2")
    [ -n "$v" ] && db_set "$1" "$v"
    return 0
}

seed jray-server/server-id       JRAY_SERVER_ID
seed jray-server/bind            JRAY_BIND
seed jray-server/trusted-proxies JRAY_TRUSTED_PROXIES
seed jray-server/contact         JRAY_CONTACT

# The API key is deliberately NOT seeded back into the prompt: it is a password
# template, so debconf would render it as a filled-in field the operator cannot
# read, and accepting it would just rewrite what is already there. Blank means
# "keep the existing key" and postinst implements exactly that.

db_fget jray-server/publish-peer-directory seen || RET=""
if [ "$RET" != "true" ] && [ "$(env_value JRAY_PUBLISH_PEER_DIRECTORY)" = "1" ]; then
    db_set jray-server/publish-peer-directory true
fi

db_input high   jray-server/server-id            || true
db_input high   jray-server/bind                 || true
db_input high   jray-server/trusted-proxies      || true
db_input high   jray-server/tmdb-api-key         || true
db_input medium jray-server/contact              || true
db_input medium jray-server/publish-peer-directory || true
db_go || true

exit 0
