-
Notifications
You must be signed in to change notification settings - Fork 0
/
rand-file
148 lines (118 loc) · 2.6 KB
/
rand-file
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#!/bin/bash
## $PROG 1.0.0 - Generate randoms files and checks their integrity
##
## Usage: $PROG [OPTION...] [COMMAND]...
## Options:
## -s, --size SIZE=4K Size (numfmt iec accepted: 1K, 1M, 1G...) of random bytes per file.
## -n, --number NUMBER=1 Number of files to generate
## -c, --checksum CHECKSUM=sha1sum Checksum function to verify the files. Use none for no verification.
## Commands:
## -h, --help Displays this help and exists
## -v, --version Displays output version and exists
## -d, --delete Clears all the generated files
## Examples:
## $PROG -s 1G -n 5 -c sha512sum
## $PROG -s 1G -n 5 -c none
SCRIPT_DIR="$(dirname "$0")"
PROG=${0##*/}
set -o errexit
# Configs
size=4K
count=1
checksum=sha1sum
# Commands
help()
{
grep "^##" "$0" | sed -e "s/^...//" -e "s/\$PROG/$PROG/g"
exit 0
}
version()
{
help | head -1
exit 0
}
delete()
{
rm ./random-*.bin
rm ./checksums-*.txt
exit 0
}
# Helper functions
echoerr()
{
echo "$@" 1>&2
}
repl()
{
printf "$1"'%.s' $(eval "echo {1.."$(($2))"}")
}
clearLine()
{
printf "\r"
repl " " $1
printf "\r"
}
clearPrintLast=""
clearPrint()
{
clearLine ${#clearPrintLast}
clearPrintLast="$@"
printf "$@"
}
none()
{
:
}
# Args Config functions
size()
{
size=$1
return 1
}
number()
{
if test -z $1; then
count=1
elif test $1 -lt 1; then
echoerr "Count argument must be more than 1"
exit 1
fi
count=$1
return 1
}
checksum()
{
checksum=$1
return 1
}
# Parsing CLI Args
[ $# = 0 ] && help
while [ $# -gt 0 ]; do
CMD=$(grep -m 1 -Po "^## *$1, --\K[^= ]*|^##.* --\K${1#--}(?:[= ])" ${SCRIPT_DIR}/${PROG} | sed -e "s/-/_/g")
if [ -z "$CMD" ]; then echo "ERROR: Command '$1' not supported"; exit 1; fi
shift; eval "$CMD" $@ || shift $? 2> /dev/null
done
# Entry
basename=random-$size-
size=$(numfmt --from=iec $size)
checksumFile="checksums-${checksum}.txt"
printf "" > ${checksumFile}
for i in $(seq 1 $count); do
file=${basename}${i}.bin
clearPrint "Generating ${file}"
head -c ${size} /dev/urandom > ${file}
clearPrint "Checking ${file}"
fileSize=$(stat --printf="%s" ${file})
if test $fileSize -ne $size; then
echoerr "File size miss match. Target: ${size} Actual: ${fileSize}"
exit 1
fi
$checksum ${file} >> ${checksumFile}
clearPrint "Done ${file}\n"
done
if test "$checksum" = "none"; then
rm ${checksumFile}
exit
fi
echo "Verifying files"
$checksum -c ${checksumFile}