#!/bin/bash

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

## usage:
## dm-reprepro-wrapper listmatched local "*"

#set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit

true "INFO: Currently running script: ${BASH_SOURCE[0]} $*"

dist_build_source_run="true"
dist_build_one_parsed="true"

MYDIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" && pwd )"

if [ "$MYDIR" = "/usr/bin" ]; then
   true "INFO: Run from: /usr/bin"
   ## XXX: hardcoded path
   derivative_maker_source_code_dir="$HOME/derivative-maker"
else
   true "INFO: Run from: source code folder"
   derivative_maker_source_code_dir="$(cd -- "$MYDIR" && cd -- "../../../../../" && pwd)"
fi

source "$derivative_maker_source_code_dir/help-steps/pre"
source "$derivative_maker_source_code_dir/help-steps/variables"

reprepro_wrap() {
   reprepro_exit_code="0"

   local reprepro_command
   reprepro_command=(
      reprepro \
      "${dist_build_reprepro_folder_options[@]}" \
      "$@"
   )

   printf '%s\n' "${bold}${cyan}INFO: (#grep-ignore-marker#) reprepro_command:${reset} ${reprepro_command[*]}"

   reprepro_output="$("${reprepro_command[@]}" 2>&1)" \
      || { reprepro_exit_code="$?" ; true; };

   if printf '%s\n' "$reprepro_output" | grep --ignore-case "is already registered with different checksums!" &>/dev/null; then
      error "Not added. Because is already registered with different checksums."
   fi

   if printf '%s\n' "$reprepro_output" | grep --ignore-case "Will not copy as not found" &>/dev/null; then
      error "Will not copy as not found!"
   fi

   printf '%s\n' "${bold}${cyan}INFO (#grep-ignore-marker#): reprepro_output:${reset}"
   printf '%s\n' "$reprepro_output"

   true "INFO: Ok."

   return "$reprepro_exit_code"
}

main() {
   ## Variable derivative_repository_name gets set by packages/kicksecure/genmkfile/usr/share/genmkfile/make-helper-one.bsh
   ## make_reprepro_codename_item is defaulted inside set_dist_build_reprepro_folder_options.
   set_dist_build_reprepro_folder_options
   reprepro_wrap "$@"
}

main "$@"
