Created
April 11, 2017 17:48
-
-
Save tekwiz/0431e8b799fd40de2c29bb41b1f2ae8e to your computer and use it in GitHub Desktop.
Update clock (raspberry pi)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
SERVICE_TIMEOUT=5 # seconds | |
NTP_SERVER=time.nist.gov | |
NTPD_PIDFILE=/var/run/ntpd.pid | |
log() { | |
[ $# -lt 2 ] && echo "Invalid call to log(): too few arguments" 1>&2 && exit 1 | |
local lev="$1" ; shift | |
local fmt="$1\n" ; shift | |
printf "$fmt" "$@" | logger -s -t "$(basename $0)" -p user.$lev | |
} | |
[ "$USER" != "root" ] && log error "Only root can run this script" && exit 1 | |
#TODO fix?? and use ntpd_is_running() | |
# ntpd_is_running() { | |
# if [[ -f $NTPD_PIDFILE ]]; then | |
# ntpd_pid=$( cat /var/run/ntpd.pid ) | |
# if [[ -z "$( ps --no-headers $ntpd_pid )" ]]; then | |
# return 1 | |
# fi | |
# fi | |
# return 0 | |
# } | |
if [[ -f $NTPD_PIDFILE ]]; then | |
log info 'Stopping NTPd...' | |
service ntp stop | |
[ $? -ne 0 ] && log error 'Failed to stop NTPd' && exit 1 | |
for (( i=1; i < $SERVICE_TIMEOUT; i++ )); do | |
sleep 1 ; [ ! -f $NTPD_PIDFILE ] && i=$SERVICE_TIMEOUT | |
done | |
[ -f $NTPD_PIDFILE ] && log error 'Failed to stop NTPd' && exit 1 | |
fi | |
log info 'Forcing time update...' | |
ntpd -4nNgq -u ntp:ntp -c /dev/stdin -l /dev/stdout <<EOCONFIG | |
server $NTP_SERVER | |
EOCONFIG | |
[ $? -ne 0 ] && log error 'Failed to force time update' && exit 2 | |
log info 'Restarting NTPd...' | |
service ntp start | |
[ $? -ne 0 ] && log error 'Failed to restart NTPd' && exit 1 | |
for (( i=1; i < $SERVICE_TIMEOUT; i++ )); do | |
sleep 1 ; [ -f $NTPD_PIDFILE ] && i=$SERVICE_TIMEOUT | |
done | |
[ ! -f $NTPD_PIDFILE ] && log error 'Failed to restart NTPd' && exit 1 | |
ntpd_pid=$( cat /var/run/ntpd.pid ) | |
[ -z "$( ps --no-headers $ntpd_pid )" ] && log error 'Failed to restart NTPd' && exit 1 | |
log info 'Saving fake-hwclock...' | |
fake-hwclock save force | |
[ $? -ne 0 ] && log error 'Failed to save fake-hwclock' && exit 1 | |
log notice 'Updated clock via NTP' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment