#!/bin/bash

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

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!" >&2
  exit 4
fi

exit_handler() {
  if [ -z "${temp_dir-}" ]; then
    return 0
  fi
  safe-rm -r -f -- "$temp_dir"
}

trap exit_handler EXIT

[ -n "${temp_dir-}" ] || temp_dir="$(mktemp --directory)"
if ! test -w "$temp_dir"; then
  printf '%s\n' "$0: ERROR: temp_dir '$temp_dir' not writeable!" >&2
  exit 5
fi

cat -- "$source_file" |
  gpg \
    --dearmor \
    --no-options \
    --homedir "$temp_dir" \
    --no-default-keyring |
  tee -- "$target_file" >/dev/null

if ! test -r "$target_file"; then
  printf '%s\n' "$0: ERROR: target_file '$target_file' not readable after writing!" >&2
  exit 6
fi

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