#!/bin/bash

# stop on any unhandled error
set -e

# @TODO: pipefail not in POSIX
set -o pipefail

# shellcheck source=src/container/output.inc.sh
source "/output.inc.sh"

# Read shell scripts into arrays (empty if no matches)
mapfile -t SH_SCRIPTS < <(grep -rlnw debian/ -e '^#!.*/sh' | sort -u || true)
mapfile -t BASH_SCRIPTS < <(grep -rlnw debian/ -e '^#!.*/bash' | sort -u || true)

SHELLCHECK_DIFF=$(mktemp)

# Run Shellcheck only if files of the type were found
if [ "${#SH_SCRIPTS[@]}" -gt 0 ]
then
  # Don't stop on findings
  # Exclude SC2250: "Prefer putting braces around variable references even when not strictly required"
  echo "++ shellcheck -x --enable=all --exclude=SC2250 --shell=sh" "${SH_SCRIPTS[@]}"
  shellcheck -x --enable=all --exclude=SC2250 --shell=sh "${SH_SCRIPTS[@]}" || true
  shellcheck -x --enable=all --exclude=SC2250 --format=diff --shell=sh "${SH_SCRIPTS[@]}" >> "$SHELLCHECK_DIFF" || true
fi

if [ "${#BASH_SCRIPTS[@]}" -gt 0 ]
then
  # Don't stop on findings
  # Exclude SC2250: "Prefer putting braces around variable references even when not strictly required"
  echo "++ shellcheck -x --enable=all --exclude=SC2250 --shell=bash" "${BASH_SCRIPTS[@]}"
  shellcheck -x --enable=all --exclude=SC2250 --shell=bash "${BASH_SCRIPTS[@]}" || true
  shellcheck -x --enable=all --exclude=SC2250 --format=diff --shell=bash "${BASH_SCRIPTS[@]}" >> "$SHELLCHECK_DIFF" || true
fi

# Apply patch if not empty, otherwise just remove it
if [[ -s "$SHELLCHECK_DIFF" ]]
then
  # Extra newline for better legibility
  echo
  patch --quiet --strip=1 < "$SHELLCHECK_DIFF"
fi
rm -f "$SHELLCHECK_DIFF"

# Commit formatting changes if any files were modified by the tools above
if ! git diff --quiet
then
  git commit -a -F - <<'EOF'
Fix issues found by Shellcheck

Apply all fixes suggested by Shellcheck that can be applied automatically in
a way that is unlikely to change functionality, only make the syntax more
robust to protect from unintentional use and side effect.
EOF
fi
