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

true "INFO: Currently running script: $BASH_SOURCE $@"

dist_build_internal_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/colors"
source "$derivative_maker_source_code_dir/help-steps/variables"

reprepro_wrap() {
   reprepro_exit_code="0"
   reprepro_output="$(reprepro \
      $dist_build_reprepro_signing_options \
      $dist_build_reprepro_folder_options \
      "$@" 2>&1)" \
      || { reprepro_exit_code="$?" ; true; };

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

   if printf '%s\n' "$reprepro_output" | grep --ignore-case "Will not copy as not found" >/dev/null 2>/dev/null; then
      true "ERROR: Will not copy as not found!"
      exit 1
   fi

   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
   true "derivative_repository_name before : $derivative_repository_name"
   true "make_reprepro_codename_item before: $make_reprepro_codename_item"
   set_dist_build_reprepro_folder_options
   true "derivative_repository_name after  : $derivative_repository_name"
   true "make_reprepro_codename_item after : $make_reprepro_codename_item"
   reprepro_wrap "$@"
}

main "$@"
