#!/bin/bash
#
# shellcheck disable=SC1091,SC2053,SC2086,SC2162
#
# Copyright (c) 2023-2026 openmediavault plugin developers
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# version: 0.3.0

export LC_ALL=C.UTF-8

declare -i count=0
declare -i index=0

. /usr/share/openmediavault/scripts/helper-functions

email_mode=""
email_comment=""
filter=""
uuid=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    -e) email_mode="$2"; shift 2 ;;
    -c) email_comment="$2"; shift 2 ;;
    -u) uuid="$2"; shift 2 ;;
    -f) filter="$2"; shift 2 ;;
    *)  if [[ -z "${filter}" ]]; then filter="$1"; fi; shift ;;
  esac
done

if [[ "${filter}" == "*" ]]; then
  filter=""
elif [[ "${filter}" == *","* ]]; then
  filter="@(${filter//,/|})"
fi

excludefilter=""
if omv_isuuid "${uuid}"; then
  excludefilter="$(omv_config_get "/config/services/compose/jobs/job[uuid='${uuid}']/excludefilter")"
fi
if [[ "${excludefilter}" == *","* ]]; then
  excludefilter="@(${excludefilter//,/|})"
fi

tmpfile=""
if [ -n "${email_mode}" ]; then
  tmpfile=$(mktemp)
  exec > "${tmpfile}" 2>&1
fi

_send_email() {
  local rc="$1"
  if [ -n "${tmpfile}" ] && [ -f "${tmpfile}" ]; then
    if [ "${email_mode}" = "always" ] || { [ "${email_mode}" = "onerror" ] && [ "${rc}" -ne 0 ]; }; then
      mail -E -s "Cron${email_comment:+ - ${email_comment}}" -a "From: Cron Daemon <root>" root < "${tmpfile}" > /dev/null 2>&1
    fi
    rm -f "${tmpfile}"
  fi
}
trap '_send_email $?' EXIT

overall_rc=0
xpath="/config/services/compose/files/file"
count=$(omv_config_get_count "${xpath}")
index=1
while [ ${index} -le ${count} ]; do
  pos="${xpath}[position()=${index}]"
  name=$(omv_config_get "${pos}/name")
  if [ -n "${filter}" ] && [[ "${name}" != ${filter} ]]; then
    index=$(( index + 1 ))
    continue
  fi
  if [ -n "${excludefilter}" ] && [[ "${name}" == ${excludefilter} ]]; then
    index=$(( index + 1 ))
    continue
  fi
  echo ${name}
  omv-compose-update "${name}" || overall_rc=$?
  index=$(( index + 1 ))
done

exit "${overall_rc}"
