#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-11-06; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.live.builder
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing || return "${ERR_GUARD_SRCE}"

#######################################
# Init GNUPGHOME.
# Globals:
#   BASH_SOURCE
#   GNUPGHOME
#   VAR_CDLB_INSIDE_RUNNER
#   VAR_EARLY_DEBUG
#   VAR_HANDLER_BUILD_DIR
#   VAR_SIGNER
#   VAR_SIGNING_CA
#   VAR_SIGNING_CA_FPR
#   VAR_SIGNING_KEY
#   VAR_SIGNING_KEY_FPR
#   VAR_SIGNING_KEY_PASS
#   VAR_SIGNING_KEY_PASSFILE
#   VAR_TMP_SECRET
#   VAR_VERIFY_KEYRING
#   VAR_WORKDIR
# Arguments:
#   None
# Returns:
#   0: on success
#   ERR_GPG__AGENT: on failure
#######################################
init_gnupg() {
  printf "\e[95m++++ ++++ ++++ ++++ ++++ ++++ ++ 🧪 %s starting ... \e[0m\n" "${BASH_SOURCE[0]}"

  if [[ "${VAR_SIGNER}" == "true" ]]; then

    __umask=$(umask)
    umask 0077

    ### Avoid collision with Gitea runner workflows.
    if [[ "${VAR_CDLB_INSIDE_RUNNER}" != "true" ]]; then

      printf "\e[93m++++ ++++ ++++ ++++ ++++ ++++ ++ 🔐 VAR_CDLB_INSIDE_RUNNER: [%s] \e[0m\n" "${VAR_CDLB_INSIDE_RUNNER}"

      declare -grx GNUPGHOME="${VAR_WORKDIR}/cdlb_$$_gnupg"

      # shellcheck disable=SC2174
      mkdir -p -m 0700 "${GNUPGHOME}"

      cat << EOF >| "${GNUPGHOME}/gpg-agent.conf"
allow-loopback-pinentry
pinentry-program /usr/bin/pinentry-tty
EOF

      if ! gpgconf --launch gpg-agent 2>&1; then

        printf "\e[91m++++ ++++ ++++ ++++ ++++ ++++ ++ ❌ Failed to launch gpg-agent. \e[0m\n"
        return "${ERR_GPG__AGENT}"

      fi

    else

      printf "\e[93m++++ ++++ ++++ ++++ ++++ ++++ ++ 🔐 VAR_CDLB_INSIDE_RUNNER: [%s] leaving GNUPGHOME untouched.\e[0m\n" "${VAR_CDLB_INSIDE_RUNNER}"

    fi

    ### Use pubring as verification keyring reference.
    declare -grx VAR_VERIFY_KEYRING="${GNUPGHOME}/pubring.kbx"

    declare -grx VAR_SIGNING_KEY_PASSFILE="${VAR_TMP_SECRET}/${VAR_SIGNING_KEY_PASS}"

    ### No tracing for security reasons ------------------------------------------------------------------------------------------
    [[ "${VAR_EARLY_DEBUG}" == "true" ]] && set +x

    declare __pw=""
    __pw="$(<"${VAR_SIGNING_KEY_PASSFILE}")"; __pw="${__pw%$'\r'}"; printf '%s' "${__pw}" >| "${VAR_SIGNING_KEY_PASSFILE}"
    __pw="" && unset __pw

    ### Turn on tracing again ----------------------------------------------------------------------------------------------------
    [[ "${VAR_EARLY_DEBUG}" == "true" ]] && set -x

    if ! gpg --batch --yes --pinentry-mode=loopback --passphrase-file "${VAR_SIGNING_KEY_PASSFILE}" --import "${VAR_TMP_SECRET}/${VAR_SIGNING_KEY}"; then

      printf "\e[91m++++ ++++ ++++ ++++ ++++ ++++ ++ ❌ Failed to import signing key. \e[0m\n"
      return "${ERR_GPG__AGENT}"

    fi

    ### Optionally, import offline GPG CA public keys.
    if [[ -n "${VAR_SIGNING_CA}" ]]; then

      # shellcheck disable=SC2155
      declare -gx VAR_SIGNING_CA_FPR="$(
        gpg --batch --with-colons --import-options show-only --import "${VAR_TMP_SECRET}/${VAR_SIGNING_CA}" \
          | awk -F: '$1=="pub"{seen_pub=1; next} seen_pub && $1=="fpr"{print $10; exit}'
      )"

      if ! gpg --batch --import "${VAR_TMP_SECRET}/${VAR_SIGNING_CA}"; then

        printf "\e[91m++++ ++++ ++++ ++++ ++++ ++++ ++ ❌ Failed to import CA public key. \e[0m\n"
        return "${ERR_GPG__AGENT}"

      fi

    fi

    shred -fzu -n 5 -- "${VAR_TMP_SECRET}/${VAR_SIGNING_KEY}"
    shred -fzu -n 5 -- "${VAR_TMP_SECRET}/${VAR_SIGNING_CA}"

    ### Export public key for verification inside ISO / chroot.
    install -d -m 0755 -o root -g root "${VAR_HANDLER_BUILD_DIR}/config/includes.chroot/etc/ciss/keys"
    install -d -m 0755 -o root -g root "${VAR_HANDLER_BUILD_DIR}/config/includes.binary"
    gpg --batch --yes --export "${VAR_SIGNING_KEY_FPR}" >| "${VAR_HANDLER_BUILD_DIR}/config/includes.chroot/etc/ciss/keys/${VAR_SIGNING_KEY_FPR}.gpg"
    gpg --batch --yes --export "${VAR_SIGNING_KEY_FPR}" >| "${VAR_HANDLER_BUILD_DIR}/config/includes.binary/${VAR_SIGNING_KEY_FPR}.gpg"
    [[ -n "${VAR_SIGNING_CA}" ]] && gpg --batch --yes --export "${VAR_SIGNING_CA_FPR}" >| "${VAR_HANDLER_BUILD_DIR}/config/includes.chroot/etc/ciss/keys/${VAR_SIGNING_CA_FPR}.gpg"
    [[ -n "${VAR_SIGNING_CA}" ]] && gpg --batch --yes --export "${VAR_SIGNING_CA_FPR}" >| "${VAR_HANDLER_BUILD_DIR}/config/includes.binary/${VAR_SIGNING_CA_FPR}.gpg"

    umask "${__umask}"
    __umask=""

  fi

  printf "\e[92m++++ ++++ ++++ ++++ ++++ ++++ ++ ✅ %s successfully applied. \e[0m\n" "${BASH_SOURCE[0]}"

  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f init_gnupg
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
