#!/bin/bash

WHERE="https://codeberg.org/api/v1/repos/johann1764/shlinters/raw/"

FILES=(
   end-of-file-fixer.sh
   get_u_codespell.sh
   get_smd.sh
   GPL3.txt
   parallel.sh
   trailing-whitespace.sh
   line-endings.sh
   expand-tabs.sh
   update.sh
   Readme.md
)

cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null || exit 1

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then cat << EOF
usage  $(basename "$0")
  Updates this directory ($(pwd)) with the latest scripts from the shlinters project.

  Outputs the download summary and the diff applied.

  If codespell is there, it is also updated.
EOF
exit
fi

DIR="$(mktemp --suffix='_downloaded' -d)"
trap 'rm -fr "$DIR"' EXIT

for name in "${FILES[@]}" ; do
   wget -nv -P "$DIR" "$WHERE$name" &
done
wait
echo >&2

diff -x 'dictionary*.txt' -x 'lex*.txt' -x '.*' --color=always "./" "$DIR/" |
sed -e 's/^diff\( -x [^ ]*\)*/diff /' -e "s/'--color=always' //" |
if grep "^" ; then
   res=0
   echo >&2
   for f in "$DIR/"* ; do
      if [ -f ".${f#"$DIR"}" ] && cmp -s "$f" ".${f#"$DIR"}" ; then
         rm "$f"
      else
         res=1
         cp -v "$f" .
      fi
   done
   chmod +x -- *.sh
   exit $res
else
   echo -e '\e[32malready up to date\e[m' >&2
fi
echo >&2

if [ -f "./u_codespell/update.sh" ] ; then
   ./u_codespell/update.sh
fi

if [ -f "./smd/smd.sh" ] ; then
   ./get_smd.sh
fi
