#!/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

command -v sq >/dev/null

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

sq packet dearmor --overwrite --output "$target_file" -- "$source_file"

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."
