#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.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.installer
# SPDX-Security-Contact: security@coresecret.eu
# SPDX-Comment: unlock_wrapper_signer.sh for signing unlock_wrapper.sh

set -Ceuo pipefail

### Paths
declare -r SCRIPT="/etc/initramfs-tools/files/unlock_wrapper.sh"
declare -r KEYFILE="/root/.ciss/keys/dummy_0x12345678_SECRET.asc"
declare -r GNUPGHOME="/root/.ciss/gnupg"

### Output Files
declare -r HASH384="${SCRIPT}.sha384"
declare -r HASH512="${SCRIPT}.sha512"
declare -r SIG384="${HASH384}.sig"
declare -r SIG512="${HASH512}.sig"

### Ensure GNUPGHOME exists with secure permissions
mkdir -p "${GNUPGHOME}"
chmod 0700 "${GNUPGHOME}"

### Import private key only if not already present
if ! gpg --homedir "${GNUPGHOME}" --list-secret-keys | grep -q "sec"; then
  printf "\e[0;92m✅ Importing private key ... \e[0m\n"
  gpg --homedir "${GNUPGHOME}" --import "${KEYFILE}"
else
  printf "\e[0;92m✅ Private key already present in keyring. \e[0m\n"
fi

### Extract fingerprint of the first secret key
# shellcheck disable=SC2155
declare -r FPR=$(gpg --homedir "$GNUPGHOME" --list-secret-keys --with-colons | awk -F: '/^fpr:/ { print $10; exit }')

if [[ -z "${FPR}" ]]; then
  printf "\e[0;91m✘ Error: Could not extract fingerprint from keyring. \e[0m\n" >&2
  exit 1
fi

printf "\e[0;92m✅ Using GPG key fingerprint: [%s] \e[0m\n" "${FPR}"

### Hashing (only the hash value, no filename)
printf "\e[0;95m🔢 Generating Hashes ... \e[0m\n"

if sha384sum "${SCRIPT}" | awk '{print $1}' >| "${HASH384}"; then
  printf "\e[0;92m✅ Hash: [%s] of Script: [%s] created. \e[0m\n" "${HASH384}" "${SCRIPT}"
fi

if sha512sum "${SCRIPT}" | awk '{print $1}' >| "${HASH512}"; then
  printf "\e[0;92m✅ Hash: [%s] of Script: [%s] created. \e[0m\n" "${HASH512}" "${SCRIPT}"
fi

printf "\e[0;92m🔢 Generating Hashes done. \e[0m\n"

### Signing Hashes
printf "\e[0;95m✍️ Signing hashes ... \e[0m\n"

if gpg --homedir "${GNUPGHOME}" --batch --yes --local-user "${FPR}" --output "${SIG384}" --detach-sign "${HASH384}"; then
  printf "\e[0;92m✅ Hash: [%s] signed: [%s]. \e[0m\n" "${HASH384}" "${SIG384}"
fi

if gpg --homedir "${GNUPGHOME}" --batch --yes --local-user "${FPR}" --output "${SIG512}" --detach-sign "${HASH512}"; then
  printf "\e[0;92m✅ Hash: [%s] signed: [%s]. \e[0m\n" "${HASH512}" "${SIG512}"
fi

printf "\e[0;92m✍️ Signing hashes done.  \e[0m\n"

exit 0

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
