-
Notifications
You must be signed in to change notification settings - Fork 7
/
get-data.sh
executable file
·89 lines (72 loc) · 2.39 KB
/
get-data.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env bash
#
# usage: get-data.sh external-data.txt
#
# external-data.txt file must contain lines of the format:
#
# PATH URL SHA256SUM
#
# get-data.sh will attempt to download the file at URL into PATH (relative to
# the location of external-data.txt) after verifying that the sha256sum is
# identical to SHA256SUM. Neither field can contain spaces.
set -o errexit
set -o pipefail
set -o nounset
if [ "$#" -ne "1" ] && ([ "$#" -ne "2" ] || [ "x$2" -ne "x-t" ]); then
echo "Usage: $0 [-t] FILE"
echo "FILE must be a file containing lines of the format:"
echo " PATH URL SHA256SUM"
echo "$0 will attempt to download the file at URL into PATH (relative to"
echo "the location of external-data.txt) after verifying that the sha256sum is"
echo "identical to SHA256SUM. Neither field can contain spaces."
echo "If -t is passed, delete the file after downloading it. This is used for testing."
exit 3
fi
if [ -z "$(which sha256sum)" ]; then
echo "Error: sha256sum could not be found."
exit 4
fi
if [ -z "$(which curl)" ]; then
echo "Error: curl could not be found."
exit 5
fi
DELETE=false
if [ "$#" -eq "1" ]; then
FILE=$1
elif [ "$#" -eq "2" ]; then
FILE=$2
DELETE=true
fi
function longest_line() { cat "$FILE" | awk '{print length($FILE)}' | sort -nr | head -1 ; }
BASEDIR=$(dirname "$FILE")
n=$(longest_line "$FILE")
while read -r OUTPUT URL CHECKSUM; do
printf "%-${n}s: " "$OUTPUT"
if [ -f "$OUTPUT" ]; then
echo -n "File exists, verifying checksum... "
COMPUTED_SUM=$(sha256sum "$OUTPUT" | cut -f 1 -d ' ')
if [ "$COMPUTED_SUM" = "$CHECKSUM" ]; then
echo "OK."
continue
else
echo "Invalid checksum!"
echo "Expected $CHECKSUM, got $COMPUTED_SUM."
echo "Deleting file and redownloading."
rm "$OUTPUT"
fi
fi
echo "File missing, downloading..."
mkdir -p "${BASEDIR}/$(dirname "$OUTPUT")"
curl --fail "$URL" --output "${BASEDIR}/${OUTPUT}"
COMPUTED_SUM=$(sha256sum "${BASEDIR}/${OUTPUT}" | cut -f 1 -d ' ')
if [ "$COMPUTED_SUM" != "$CHECKSUM" ]; then
echo "Error: Invalid checksum of downloaded file!"
echo "Expected: $CHECKSUM"
echo "Got: $COMPUTED_SUM"
exit 1
fi
if [ "$DELETE" = "true" ]; then
rm -f "${BASEDIR}/${OUTPUT}"
fi
done < "$FILE"
echo "Done."