a8e72fabe332311cf5bad677e80062029c643e65
[fake-hwclock.git] / fake-hwclock
1 #!/bin/sh
2 #
3 # Trivial script to load/save current contents of the kernel clock
4 # from/to a file. Helpful as a *bootstrap* clock on machines where
5 # there isn't a useful RTC driver (e.g. on development boards). Using
6 # NTP is still recommended on these machines to get to real time sync
7 # once more of the system is up and running.
8 #
9 # Copyright 2012-2016 Steve McIntyre <93sam@debian.org>
10 #
11 # License: GPLv2, see COPYING
12
13 if [ "$FILE"x = ""x ] ; then
14     FILE=/etc/fake-hwclock.data
15 fi
16
17 # Midnight on the day of this release, used as a sanity check when
18 # saving
19 HWCLOCK_EPOCH="2016-04-15 00:00:00"
20 HWCLOCK_EPOCH_SEC="1460678400"
21
22 COMMAND=$1
23 if [ "$COMMAND"x = ""x ] ; then
24     COMMAND="save"
25 fi
26
27 FORCE=false
28 if [ "$2"x = "force"x ] ; then
29     FORCE=true
30 fi
31
32 case $COMMAND in
33     save)
34         if [ -e $FILE ] ; then
35             NOW_SEC=$(date -u '+%s')
36             if $FORCE || [ $NOW_SEC -ge $HWCLOCK_EPOCH_SEC ] ; then
37                 date -u '+%Y-%m-%d %H:%M:%S' > $FILE
38             else
39                 echo "Time travel detected!"
40                 echo "fake-hwclock release date is in the future: $HWCLOCK_EPOCH"
41                 echo "Current system time: $(date -u '+%Y-%m-%d %H:%M:%S')"
42                 echo "To force the saved system clock backwards in time anyway, use \"force\""
43             fi
44         else
45             date -u '+%Y-%m-%d %H:%M:%S' > $FILE
46         fi
47         ;;
48     load)
49         if [ -e $FILE ] ; then
50             SAVED="$(cat $FILE)"
51             SAVED_SEC=$(date -u -d "$SAVED" '+%s')
52             NOW_SEC=$(date -u '+%s')
53             if $FORCE || [ $NOW_SEC -le $SAVED_SEC ] ; then
54                 date -u -s "$SAVED"
55             else
56                 echo "Current system time: $(date -u '+%Y-%m-%d %H:%M:%S')"
57                 echo "fake-hwclock saved clock information is in the past: $SAVED"
58                 echo "To set system time to this saved clock anyway, use \"force\""
59             fi      
60         else
61             echo "Unable to read saved clock information: $FILE does not exist"
62         fi
63         ;;
64     *)
65         echo $0: Unknown command $COMMAND
66         exit 1
67         ;;
68 esac