#!/bin/bash

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

## This script is used by package 'anon-shared-build-apt-sources-tpo'.

#set -x
set -o errexit
set -o errtrace
set -o nounset
set -o pipefail

source_file="$1"
target_file="$2"

if [ "$source_file" = "" ] || [ "$target_file" = "" ]; then
   printf '%s\n' "$0: ERROR: syntax: $0 source-file target-file" >&2
   exit 2
fi

if ! test -r "$source_file" ; then
   printf '%s\n' "$0: ERROR: source file '$source_file' does not exist or not readable!" >&2
   exit 3
fi

target_folder="${target_file%/*}"

if ! test -w "$target_folder" ; then
   printf '%s\n' "$0: ERROR: target_folder '$target_folder' not writeable!

By Debian default, root rights are required to write to folder '/etc/apt/trusted.gpg.d'.

Perhaps prepending 'sudo' would help? Consider:

sudo $0 $source_file $target_file" >&2
   exit 4
fi

command=( sq cert lint --cert-file "$source_file" )
if ! "${command[@]}" &>/dev/null; then
   printf '%s\n' "$0: ERROR: Command '${command[*]} failed.' Re-running to show output:"
   "${command[@]}" || exit 5
   exit 5
fi

## 'gpg-dearmor' is no longer required.
## Nowadays APT as of Debian 'trixie':
## * Has native '.asc' (gpg armored file) support.
## * Permits mixing '.asc' (gpg armored public key file) with '.gpg' (gpg binary public key file).
#gpg-dearmor "$source_file" "$target_file"
cp --verbose -- "$source_file" "$target_file"

command=( sq cert lint --cert-file "$target_file" )
if ! "${command[@]}" &>/dev/null; then
   printf '%s\n' "$0: ERROR: Command '${command[*]} failed.' Re-running to show output:"
   "${command[@]}" || exit 5
   exit 7
fi

printf '%s\n' "$0: INFO: OK."
