1 | #!/bin/sh
|
---|
2 | #
|
---|
3 | # Update an single file (content via stdin) on the flash disk if the md5 does
|
---|
4 | # not match. This script tries to be on the safe side by checking md5 at
|
---|
5 | # various stages.
|
---|
6 | #
|
---|
7 | # TODO: Maybe rsync is also able to perform the mount and umount before and
|
---|
8 | # after, this will eliminate all the hacking with md5 checks.
|
---|
9 | #
|
---|
10 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
11 | #
|
---|
12 |
|
---|
13 | if [ -z "$1" ]; then
|
---|
14 | echo "Usage: $0 <filepath> [<md5sum> [<file mode bits> [<file ownership>]]]" 1>&2
|
---|
15 | exit 128
|
---|
16 | fi
|
---|
17 |
|
---|
18 | FILE=$1
|
---|
19 | NEW_MD5=${2:-""}
|
---|
20 | MODE_BITS=${3:-""}
|
---|
21 | OWNERSHIP=${4:-""}
|
---|
22 |
|
---|
23 | if [ ! -f "$FILE" ]; then
|
---|
24 | echo "# ERROR: File $FILE does not exists" 1>&2
|
---|
25 | exit 1
|
---|
26 | fi
|
---|
27 |
|
---|
28 | # First try to transfer file to local system
|
---|
29 | # this restricts the filesize to the maximum size of the /tmp system
|
---|
30 | TMPFILE=`mktemp -t $(basename $0)` || exit 1
|
---|
31 | cat > $TMPFILE || exit 1
|
---|
32 | TMP_MD5="`md5 -q $TMPFILE`" || exit 1
|
---|
33 |
|
---|
34 | # Check which md5 to use, the given one or the calculated one
|
---|
35 | if [ -n "$NEW_MD5" ]; then
|
---|
36 | TARGET_MD5="$NEW_MD5"
|
---|
37 | if [ "$TMP_MD5" != "$TARGET_MD5" ]; then
|
---|
38 | echo "# ERROR: File transfer failed" 1>&2
|
---|
39 | exit 2
|
---|
40 | fi
|
---|
41 | else
|
---|
42 | TARGET_MD5="$TMP_MD5"
|
---|
43 | fi
|
---|
44 |
|
---|
45 | # Actually check whether we need to copy the file
|
---|
46 | CURRENT_MD5=`md5 -q $FILE` || exit 1
|
---|
47 | if [ "$CURRENT_MD5" != "$TARGET_MD5" ]; then
|
---|
48 | echo "# INFO: Updating $FILE; old MD5 $CURRENT_MD5"
|
---|
49 | mount -uwo noatime / || exit 1
|
---|
50 | cp -f $TMPFILE $FILE
|
---|
51 | [ -n "$MODE_BITS" ] && chmod $MODE_BITS $FILE
|
---|
52 | [ -n "$OWNERSHIP" ] && chown $OWNERSHIP $FILE
|
---|
53 | mount -ur /
|
---|
54 |
|
---|
55 | # Make sure to recheck the md5 alter write to make sure all went ok
|
---|
56 | RECHECK_MD5=`md5 -q $FILE`
|
---|
57 | echo "# INFO: Updated $FILE; new MD5 $RECHECK_MD5"
|
---|
58 | else
|
---|
59 | echo "# INFO: File $FILE already has md5 $CURRENT_MD5"
|
---|
60 | fi
|
---|