#!/bin/bash
clear
echo "called: $0 $1 $2 $3 $4 $5"

## This file organises downloads from the web using the given BOM lines.
## -- Arguments:
## $1 is the path/to/file of the BOM file.
## $2 starts with "%" if it is an argument for Windows usage, or
## $2 or even $3 is the destination/base/path, if it is not "NOPAUSE".
##   The destination/base/path should end with "/" or the last element
##   is prefixed to all file names.
## $4 may start with "%" for the Windows destination path, not used here.
## All paths should use forward slashes, also in the Windows version.
## If none of $2, $3, $4 and $5 is "NOPAUSE", execution ends with
## "...press any key" for manual start.
##
## Calling variant for Linux and Windows:
## download-from-URL "$0" "%0" "$DST/" "%DST%\" NOPAUSE
##
## Calling variant possible for both:
## download-from-URL "$0" "%0" "../dst/" NOPAUSE
##
## Calling variant for Linux usage only:
## download-from-URL "path/to/bom" "path/to/dst/" NOPAUSE
##
## -- BOM
## BOM lines start with "GET-URL " and have the form:
## GET-URL FILE; URL; SHA256-hash;
## Other lines in this file are ignored. They can contain the
## 'download-from-URL' call or any comments.
##
## -- Usage:
## This file is universally usable.
## It is licensed under the terms of the LGPL
## (Lesser General Public License) of the Free Software Foundation.
## Written by Hartmut Schorrig, Germany.
## Version from 2026-11-02.
## Note: This file was developed with assistance from ChatGPT.
## ---

## Clear error and information variables used for accumulation.
EXISTFILEOK=""
EXISTHASHFAIL=""
DOWNLOADERR=""
DOWNLOADHASHFAIL=""

## Pause only if none of arguments 2 to 5 is "NOPAUSE".
## Read from the terminal, not from the BOM file.
pause_if_needed() {
  if [[ "$1" != "NOPAUSE" && "$2" != "NOPAUSE" && "$3" != "NOPAUSE" && "$4" != "NOPAUSE" ]]; then
    if [[ -r /dev/tty ]]; then
      read -r -n 1 -s -p "...press any key" < /dev/tty || true
      echo
    fi
  fi
}
## check FILEBOM
if [[ ! -f "$1" ]]; then
  echo "ERROR: BOM file not found: $1"
  exit 5
fi
if [[ ! -r "$1" ]]; then
  echo "ERROR: BOM file exists but not readable: $1"
  exit 6
fi
## Determine the destination directory.
DST="$2"
if [[ "${DST:0:1}" == "%" ]]; then DST="$3"; fi
if [[ "$DST" == "NOPAUSE" ]]; then DST=""; fi

## Check the destination directory.
if [[ -n "$DST" && ! -d "$DST" ]]; then
  echo "$DST does not exist; it should be a directory."
  pause_if_needed "$2" "$3" "$4" "$5"
  exit 7
fi

## Read the BOM file line by line.
## IFS= prevents field splitting by read.
## -r prevents interpretation of backslashes.
while IFS= read -r LINE; do
  ## Remove a possible Windows CR at the end of the line.
  LINE="${LINE%$'\r'}"

  if [[ "${LINE:0:8}" == "GET-URL " ]]; then
    echo "==== line = $LINE"

    ## Split the BOM line into its four fields.
    IFS='; ' read -r CMD FILE URL HASH <<< "$LINE"

    ## The used FILE is relative to the destination directory.
    FILE="${DST}${FILE}"

    ## File already exists: check its hash.
    if [[ -f "$FILE" ]]; then
      HASH_LINE=$(sha256sum -- "$FILE")
      HASHACT="${HASH_LINE%% *}"

      if [[ "$HASHACT" == "$HASH" ]]; then
        echo "file exists, hash OK: $FILE"
        EXISTFILEOK="${EXISTFILEOK}${FILE}; "
      else
        echo "file exists with faulty hash: $FILE hash=$HASHACT"
        echo "^^^ERROR"
        EXISTHASHFAIL="${EXISTHASHFAIL}${FILE}; "
      fi

    else
      ## File does not exist: download it.
      echo "Download: $FILE from $URL ..."

      DIR=$(dirname -- "$FILE")
      if [[ ! -d "$DIR" ]]; then mkdir -p -- "$DIR"; fi

      if ! curl --fail --show-error --location --output "$FILE" "$URL"; then
        echo "ERROR: Download failed: $FILE $URL"
        rm -f -- "$FILE"
        echo "^^^ERROR"
        DOWNLOADERR="${DOWNLOADERR}${FILE}; "

      else
        ## Download succeeded: check its hash.
        HASH_LINE=$(sha256sum -- "$FILE")
        HASHACT="${HASH_LINE%% *}"

        if [[ "$HASHACT" == "$HASH" ]]; then
          echo "ok"
        else
          echo "ERROR: SHA-256 mismatch, file removed."
          echo "Expected hash=$HASH"
          echo "Actual hash=$HASHACT"
          echo "^^^ERROR"
          rm -f -- "$FILE"
          DOWNLOADHASHFAIL="${DOWNLOADHASHFAIL}${FILE}; "
        fi
      fi
    fi
  fi
done < "$1"

## Summary.
echo "== Downloaded files with faulty hash, removed: $DOWNLOADHASHFAIL"
echo "== Files with download error: $DOWNLOADERR"
echo "== Existing files with faulty hash: $EXISTHASHFAIL"
echo "== Files already existing, hash OK: $EXISTFILEOK"

pause_if_needed "$2" "$3" "$4" "$5"

## Exit status.
if [[ -n "$DOWNLOADHASHFAIL" ]]; then
  if [[ -n "$EXISTHASHFAIL" ]]; then
    if [[ -n "$DOWNLOADERR" ]]; then exit 16; else exit 15; fi
  fi
  if [[ -n "$DOWNLOADERR" ]]; then exit 14; else exit 13; fi
fi
if [[ -n "$EXISTHASHFAIL" ]]; then
  if [[ -n "$DOWNLOADERR" ]]; then exit 10; else exit 3; fi
fi
if [[ -n "$DOWNLOADERR" ]]; then exit 9; fi
if [[ -n "$EXISTFILEOK" ]]; then exit 1; fi
exit 0
