Early firmware update support
[gamestick-pjgsapi.git] / bin / prepare-firmware.sh
1 #!/bin/sh
2 # Prepare a firmware update file so it can be used for GameStick firmware updates
3 set -e
4
5 if ! command -v xortool-xor 2>&1 > /dev/null; then
6     echo "Error: xortool-xor not found (pip install xortool)"
7     exit 3
8 fi
9 if ! command -v xxd 2>&1 > /dev/null; then
10     echo "Error: xxd not found"
11     exit 3
12 fi
13
14 if [ $# -lt 1 ]; then
15     echo "Error: Firmware directory missing (www/firmware/x.y.z)"
16     exit 1
17 fi
18
19 if [ ! -d "$1" ]; then
20     echo "Error: Firmware directory does not exist"
21     exit 2
22 fi
23
24 fwDir=$1
25 fwFile=$1/update.img
26
27 if [ ! -f "$fwFile" ]; then
28     echo "Error: Firmware directory has no update.img"
29     exit 2
30 fi
31
32 cd "$fwDir"
33 rm chunk-* || true
34 rm tmp-* || true
35 split --bytes=102400 --numeric-suffixes --suffix-length=4 $(basename "$fwFile") tmp-part-
36
37 #xor the files with the secret key
38 for partfile in tmp-part-*; do
39     #"91" (hex 5b, binary 1011011) is the xor key
40     xortool-xor -h 5b --no-newline -f "$partfile" > "tmp-xor-$partfile"
41 done
42 #"sign" the files by prefixing the binary sha1sum
43 for xorfile in tmp-xor-*; do
44     #"91" (hex 5b, binary 1011011) is the xor key
45     num=$(echo $xorfile | sed  's/tmp-xor-tmp-part-//')
46     sha1sum "$xorfile" |cut -d' ' -f 1 | xxd -r -p > chunk-$num
47     cat $xorfile >> chunk-$num
48 done
49
50 rm tmp-* || true
51
52 #remove leading zeros
53 for num in $(seq 0 999); do
54     if [ -f "chunk-0$num" ]; then
55         mv "chunk-0$num" "chunk-$num"
56     elif [ -f "chunk-00$num" ]; then
57         mv "chunk-00$num" "chunk-$num"
58     elif [ -f "chunk-000$num" ]; then
59         mv "chunk-000$num" "chunk-$num"
60     fi
61 done
62
63 #those files may not contain newlines
64 ls -1 chunk-* | wc -l | tr -d '\n' > numchunks
65 stat --printf=%s update.img > filesize