check-sha256-and-download.sh 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #! /bin/bash
  2. # Download a file and it's sha256 checksum and validate
  3. #
  4. # Usage: check-sha256-and-download.sh FILE_URL CHECKSUM_URL
  5. #
  6. # Output:
  7. # - The name of the validated file on stdout (to allow use in further scripting)
  8. #
  9. # Errors:
  10. # - Errors, warnings on stderr
  11. # - non-zero exit status on errors.
  12. # This is bash. Be safe out there.
  13. set -e; set -u
  14. # Helper functions
  15. PROG=`basename "$0" | tr -d '\n'`
  16. function info() { echo `date +%c` ${PROG}\: info: "$@" 1>&2; }
  17. function warn() { echo `date +%c` ${PROG}\: warning: "$@" 1>&2; }
  18. function error() { echo `date +%c` ${PROG}\: error: "$@" 1>&2; }
  19. function debug() { [[ -v DEBUG ]] && echo `date +%c` ${PROG}\: debug: "$@" 1>&2 || true ; }
  20. function die() { echo `date +%c` ${PROG}\: fatal: "$@" 1>&2 && exit 1; }
  21. USAGE="$PROG FILE_URL CHECKSUM_URL"
  22. if [[ "$#" -lt 1 ]]; then
  23. warn "Missing FILE_URL"
  24. die "Uaage: $USAGE"
  25. else
  26. FILE_URL="$1" # "https://download.edge.mysocket.io/linux_arm64/mysocketctl"
  27. FILE="`basename $1`"
  28. fi
  29. if [[ "$#" -lt 2 ]]; then
  30. warn "Missing CHECKSUM_URL"
  31. die "Uaage: $USAGE"
  32. else
  33. CHECKSUM_URL="$2" # "https://download.edge.mysocket.io/linux_arm64/sha256-checksum.txt"
  34. CHECKSUM_FILE="`basename $2`"
  35. fi
  36. CURL="curl -s -S"
  37. SUM="sha256sum --quiet -c"
  38. # Always get latest checksum
  39. ${CURL} "${CHECKSUM_URL}" > "${CHECKSUM_FILE}" \
  40. || die "Failure to download mysocket sha checksum"
  41. # Check existing file against checksum or download
  42. if [ -f "${FILE}" ]; then
  43. info "Allready have file."
  44. # file already exists, check it, downlaod if failed
  45. echo "`cat ${CHECKSUM_FILE}` ${FILE}" | ${SUM} -c \
  46. || info "Checksum failed. Downloading." \
  47. && ${CURL} "${FILE_URL}" > "${FILE}" \
  48. || die "Failure to download"
  49. else
  50. info "File not found. Downloading."
  51. ${CURL} "${FILE_URL}" > "${FILE}" \
  52. || die "Failure to download"
  53. fi
  54. # Final check of checksum
  55. echo "`cat ${CHECKSUM_FILE}` ${FILE}" | ${SUM} \
  56. || die "Checksum failed. Downloading." \
  57. info "$FILE validated"
  58. echo $FILE