#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -x
set -e

true "INFO: Currently running script: $BASH_SOURCE $@"

MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

cd "$MYDIR"
cd ..
cd help-steps

dist_build_internal_run="true"

source pre
source colors
source variables

main() {
   sanity_tests "$@"
   gpg_key_create "$@"
   gpg_key_debugging "$@"
   signify_key_create "$@"
   true "INFO: END of $FUNCNAME"
}

sanity_tests() {
   command -v sq >/dev/null
   command -v sqop >/dev/null
   command -v signify-openbsd >/dev/null
}

gpg_key_create() {
   true "DEBEMAIL: $DEBEMAIL"
   ## Debugging.
   pwd

   if sq cert list --cert-email "$DEBEMAIL" &>/dev/null ; then
      true "INFO: OpenPGP key with uid DEBEMAIL $DEBEMAIL already exists. Skipping OpenPGP key creation, ok."
      return 0
   fi

   true "INFO: OpenPGP key with uid DEBEMAIL $DEBEMAIL does not exist yet. Generating OpenPGP key..."

   ## Not idempotent. (Would generate different key.)
   ##
   ## Useful for CI to test 'dm-prepare-release' image signing.
   ##
   ## 'sqop': Not stateful.
   ## * In theory, sqop would be more suitable. 'sqop' does not use 'gpg-agent'.
   ## * In practice, redistributable builds are created using Qubes 'split-gpt-2',
   ##   which is using 'gpg-agent'. Hence, 'sq' is being used.
   ## 'sqop generate-key | tee -- private-key-path >/dev/null'
   ##
   ## 'sq': Stateful.
   ## '--without-password' / '--expiration never':
   ##  * Not useful on CI.
   ## -* Users who did not study 'sq' have no benefit.
   ## -* Users that studied 'sq' manually generate the key.
   ##
   ## TODO: Debian forky: Drop or upgrade '--profile rfc9580' depending on availability.
   sq key generate --profile rfc9580 --own-key --email "$DEBEMAIL" --without-password --expiration never

   true "INFO: END of $FUNCNAME"
}

gpg_key_debugging() {
   true "INFO: show OpenPGP key fingerprint for uid DEBEMAIL"
   ## Just output list of secret keys in that very folder in case that ever breaks and someone ever sends
   ## a build log, this will help with debugging.
   ## Idempotent.
   sq cert list --cert-email "$DEBEMAIL"
   sq cert lint --cert-email "$DEBEMAIL"
}

signify_key_create() {
   mkdir --parents -- "$signify_folder"
   chmod --recursive -- og-rwx "$signify_folder"

   if test -f "$signify_private_key" ; then
      true "INFO: signify_private_key $signify_private_key already exists. Skipping signify signing key generation, ok."
      test -r "$signify_private_key"
      return 0
   fi

   true "INFO: signify_private_key $signify_private_key does not exist yet. Generating signify signing key..."
   pushd -- "$signify_folder" >/dev/null
   ## Not idempotent. (Would generate different key.)
   signify-openbsd -n -G -p "$signify_public_key" -s "$signify_private_key" -c "derivative-maker"
   popd >/dev/null

   true "INFO: END of $FUNCNAME"
}

main "$@"
