#!/bin/bash
# https://www.progressiverobot.com
# Copyright (c) 2026 Christopher Holloway / Progressive Robot Ltd
# SPDX-License-Identifier: AGPL-3.0-or-later

# The command hmailserver.set-database-password (hmailserver/docs/Snap.md): the
# database password, one line on standard input, into
# $SNAP_COMMON/secrets/database-password, root's and mode 0600, which the service
# reads as root at every start and the container image's entrypoint then writes into
# the [Database] section, as it writes HM_DB_PASSWORD. Not a snap set value: snapd
# hands those to every command of the snap, whoever runs it.
#
#   printf '%s\n' '<password>' | sudo hmailserver.set-database-password
#   sudo hmailserver.set-database-password --remove
#
# The value is held to what the configuration file can hold, as the entrypoint holds
# it (ini_value_ok): no line break or other control character, no white space at
# either end, not wrapped in matching quotation marks. It takes effect at the
# service's next start (sudo snap restart hmailserver.daemon).
set -eu

# shellcheck source=snap/local/bin/hmailserver-snap-env
. "$SNAP/bin/hmailserver-snap-env"

if [ "$(id -u)" != 0 ]; then
   echo "hmailserver.set-database-password: run it as root (sudo); the file it writes is root's alone" >&2
   exit 77
fi

hm_snap_prepare

if [ "${1:-}" = --remove ]; then
   rm -f "$HM_SNAP_DB_PASSWORD_FILE"
   echo "The database password file is removed; the service's next start writes [Database] without a password."
   exit 0
fi
if [ "$#" -ne 0 ]; then
   printf '%s\n' "usage: printf '%s\\n' '<password>' | sudo hmailserver.set-database-password   or   sudo hmailserver.set-database-password --remove" >&2
   exit 64
fi

password=""
if ! IFS= read -r password && [ -z "$password" ]; then
   echo "hmailserver.set-database-password: nothing on standard input; nothing was changed" >&2
   exit 66
fi
case "$password" in
   '')
      echo "hmailserver.set-database-password: the password is empty; --remove takes the file away instead. Nothing was changed." >&2
      exit 65 ;;
   *[[:cntrl:]]*)
      echo "hmailserver.set-database-password: the password holds a control character, which hMailServer.ini cannot hold. Nothing was changed." >&2
      exit 65 ;;
   [[:space:]]*|*[[:space:]])
      echo "hmailserver.set-database-password: the password begins or ends with white space, which hMailServer.ini does not keep. Nothing was changed." >&2
      exit 65 ;;
   \'*\'|\"*\")
      echo "hmailserver.set-database-password: the password begins and ends with the same quotation mark, which hMailServer.ini takes off. Nothing was changed." >&2
      exit 65 ;;
esac

umask 077
tmp="$(mktemp "$HM_SNAP_SECRETS/.database-password.XXXXXX")"
printf '%s' "$password" > "$tmp"
mv -f "$tmp" "$HM_SNAP_DB_PASSWORD_FILE"
echo "The database password is stored. It is used from the service's next start: sudo snap restart hmailserver.daemon"
