procd: rework trigger handling
[openwrt/openwrt.git] / package / utils / busybox / files / sysntpd
1 #!/bin/sh /etc/rc.common
2 # Copyright (C) 2011 OpenWrt.org
3
4 START=98
5
6 USE_PROCD=1
7 PROG=/usr/sbin/ntpd
8 HOTPLUG_SCRIPT=/usr/sbin/ntpd-hotplug
9
10 get_dhcp_ntp_servers() {
11 local interfaces="$1"
12 local filter="*"
13 local interface ntpservers ntpserver
14
15 for interface in $interfaces; do
16 [ "$filter" = "*" ] && filter="@.interface='$interface'" || filter="$filter,@.interface='$interface'"
17 done
18
19 ntpservers=$(ubus call network.interface dump | jsonfilter -e "@.interface[$filter]['data']['ntpserver']")
20
21 for ntpserver in $ntpservers; do
22 local duplicate=0
23 local entry
24 for entry in $server; do
25 [ "$ntpserver" = "$entry" ] && duplicate=1
26 done
27 [ "$duplicate" = 0 ] && server="$server $ntpserver"
28 done
29 }
30
31 validate_ntp_section() {
32 uci_validate_section system timeserver "${1}" \
33 'server:list(host)' 'enabled:bool:1' 'enable_server:bool:0' 'use_dhcp:bool:1' 'dhcp_interface:list(string)'
34 }
35
36 start_service() {
37 local server enabled enable_server use_dhcp dhcp_interface peer
38
39 validate_ntp_section ntp || {
40 echo "validation failed"
41 return 1
42 }
43
44 [ $enabled = 0 ] && return
45
46 [ $use_dhcp = 1 ] && get_dhcp_ntp_servers "$dhcp_interface"
47
48 [ -z "$server" ] && return
49
50 procd_open_instance
51 procd_set_param command "$PROG" -n -N
52 [ "$enable_server" = "1" ] && procd_append_param command -l
53 [ -x "$HOTPLUG_SCRIPT" ] && procd_append_param command -S "$HOTPLUG_SCRIPT"
54 for peer in $server; do
55 procd_append_param command -p $peer
56 done
57 procd_set_param respawn
58 procd_close_instance
59 }
60
61 service_triggers() {
62 local script name use_dhcp
63
64 script=$(readlink -f "$initscript")
65 name=$(basename ${script:-$initscript})
66
67 procd_open_trigger
68 procd_add_config_trigger "config.change" "system" /etc/init.d/$name reload
69
70 config_load system
71 config_get use_dhcp ntp use_dhcp 1
72
73 [ $use_dhcp = 1 ] && {
74 local dhcp_interface
75 config_get dhcp_interface ntp dhcp_interface
76
77 if [ -n "$dhcp_interface" ]; then
78 for n in $dhcp_interface; do
79 procd_add_interface_trigger "interface.*" $n /etc/init.d/$name reload
80 done
81 else
82 procd_add_raw_trigger "interface.*" 1000 /etc/init.d/$name reload
83 fi
84 }
85
86 procd_close_trigger
87
88 procd_add_validation validate_ntp_section
89 }