download 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/bash
  2. set -eu -o pipefail
  3. declare -a urls
  4. usage() {
  5. echo "Usage: download --url https://example.org/test --url https://mirror.example/blah --output test.tar --sha256 1234..abc"
  6. exit "${1:-0}"
  7. }
  8. while [ $# -gt 0 ]; do
  9. case "$1" in
  10. --url)
  11. urls+=("$2")
  12. shift
  13. ;;
  14. --output)
  15. output="$2"
  16. shift
  17. ;;
  18. --sha256)
  19. sha256="$2"
  20. shift
  21. ;;
  22. --help|-h)
  23. usage
  24. ;;
  25. *)
  26. usage 1
  27. ;;
  28. esac
  29. shift
  30. done
  31. if [ -z "${output:-}" ] || [ -z "${sha256:-}" ] || [ -z "${urls[*]}" ]; then
  32. usage 1
  33. fi
  34. if [ -n "${DL_CACHE:-}" ]; then
  35. if [ -f "$DL_CACHE/$sha256" ]; then
  36. echo "download: Found '$output' (${sha256:0:8}...) in cache."
  37. cp "$DL_CACHE/$sha256" "$output"
  38. exit 0
  39. fi
  40. fi
  41. if [ "${DL_OFFLINE:-}" == "true" ]; then
  42. echo "download: ERROR: File '$output' (${sha256:0:8}...) not found in cache and offline mode is active!"
  43. exit 1
  44. fi
  45. tmpd="$(mktemp -d -p "${DL_CACHE:-.}")"
  46. cleanup() {
  47. rm -rf "$tmpd"
  48. }
  49. trap cleanup EXIT
  50. for url in "${urls[@]}"; do
  51. echo "download: Trying to fetch $url"
  52. wget --timeout=10 -O "$tmpd/unverified" "$url" || true
  53. sha256_received="$(sha256sum "$tmpd/unverified" | cut -d ' ' -f 1)"
  54. if [ "$sha256" != "$sha256_received" ]; then
  55. echo "download: WARNING: Hash mismatch: Expected $sha256 but received $sha256_received"
  56. continue
  57. fi
  58. echo "download: Fetched '$output' (${sha256:0:8}...) successfully."
  59. if [ -n "${DL_CACHE:-}" ]; then
  60. mv "$tmpd/unverified" "$DL_CACHE/$sha256"
  61. cp "$DL_CACHE/$sha256" "$output"
  62. exit 0
  63. fi
  64. mv "$tmpd/unverified" "$output"
  65. exit 0
  66. done
  67. echo "download: ERROR: Failed to download '$output' (${sha256:0:8}...)! No URLs left to try."
  68. exit 1