#!/bin/bash
#
# shellcheck disable=SC1091
#
# 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.0.2

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

sfpath="${1}"

if [ ! -d "${sfpath}" ]; then
  echo "Invalid directory: ${sfpath}"
  exit 1
fi

echo "Removing old .git directory (if found) ..."
rm -rf "${sfpath}/.git"

echo "Initializing new git repo ..."
GIT_OPTIONAL_LOCKS=0 git init --initial-branch=main "${sfpath}" --quiet

echo "Configuring ..."
git -C "${sfpath}" config user.name "openmediavault-compose"
git -C "${sfpath}" config user.email "compose@localhost"

echo "Adding existing files to repo ..."
cd "${sfpath}" || exit 2

# Add global.env if it exists
[ -f "global.env" ] && git add global.env

# Add docker-compose relevant files
for dir in */; do
  [ -d "${dir}" ] || continue
  name="${dir%/}"
  [ -f "${dir}${name}.yml" ] && git add "${dir}${name}.yml"
  [ -f "${dir}${name}.env" ] && git add "${dir}${name}.env"
  [ -f "${dir}compose.override.yml" ] && git add "${dir}compose.override.yml"
done

# Add configs from OMV database
xpath="/config/services/compose/configs/config"
count=$(omv_config_get_count "${xpath}")

for (( index=1; index<=count; index++ )); do
  pos="${xpath}[position()=${index}]"
  if omv_config_exists "${pos}/name"; then
    cfgname="$(omv_config_get "${pos}/name")"
    cfguuid="$(omv_config_get "${pos}/fileref")"

    if [ -n "${cfgname}" ] && [ -n "${cfguuid}" ]; then
      filename="$(omv_config_get "/config/services/compose/files/file[uuid='${cfguuid}']/name")"
      if [ -n "${filename}" ]; then
        cfgpath="${filename}/${cfgname}"
        [ -f "${cfgpath}" ] && git add "${cfgpath}"
      fi
    fi
  fi
done

# Commit if there are staged changes
if git diff --cached --quiet; then
  echo "No files to commit."
else
  git commit --quiet --message "initial commit"
  echo "Initial commit created."
fi

echo "Done."

exit 0
