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

## 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
}


## Clear error and information variables used for accumulation.
##clear
echo "called: $0 $1 $2 $3 $4 $5"
EXISTFILEOK=""
EXISTHASHFAIL=""
DOWNLOADERR=""
DOWNLOADHASHFAIL=""

## 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"

##echo "== 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

