Debian Codegraph @

awklib/eg/prog/alarm.awk

raw
1 # alarm.awk --- set an alarm
2 #
3 # Requires getlocaltime() library function
4 #
5 # Arnold Robbins, [email protected], Public Domain
6 # May 1993
7 # Revised December 2010
8
9 # usage: alarm time [ "message" [ count [ delay ] ] ]
10
11 BEGIN {
12 # Initial argument sanity checking
13 usage1 = "usage: alarm time ['message' [count [delay]]]"
14 usage2 = sprintf("\t(%s) time ::= hh:mm", ARGV[1])
15
16 if (ARGC < 2) {
17 print usage1 > "/dev/stderr"
18 print usage2 > "/dev/stderr"
19 exit 1
20 }
21 switch (ARGC) {
22 case 5:
23 delay = ARGV[4] + 0
24 # fall through
25 case 4:
26 count = ARGV[3] + 0
27 # fall through
28 case 3:
29 message = ARGV[2]
30 break
31 default:
32 if (ARGV[1] !~ /[[:digit:]]?[[:digit:]]:[[:digit:]]{2}/) {
33 print usage1 > "/dev/stderr"
34 print usage2 > "/dev/stderr"
35 exit 1
36 }
37 break
38 }
39
40 # set defaults for once we reach the desired time
41 if (delay == 0)
42 delay = 180 # 3 minutes
43 if (count == 0)
44 count = 5
45 if (message == "")
46 message = sprintf("\aIt is now %s!\a", ARGV[1])
47 else if (index(message, "\a") == 0)
48 message = "\a" message "\a"
49 # split up alarm time
50 split(ARGV[1], atime, ":")
51 hour = atime[1] + 0 # force numeric
52 minute = atime[2] + 0 # force numeric
53
54 # get current broken down time
55 getlocaltime(now)
56
57 # if time given is 12-hour hours and it's after that
58 # hour, e.g., `alarm 5:30' at 9 a.m. means 5:30 p.m.,
59 # then add 12 to real hour
60 if (hour < 12 && now["hour"] > hour)
61 hour += 12
62
63 # set target time in seconds since midnight
64 target = (hour * 60 * 60) + (minute * 60)
65
66 # get current time in seconds since midnight
67 current = (now["hour"] * 60 * 60) + \
68 (now["minute"] * 60) + now["second"]
69
70 # how long to sleep for
71 naptime = target - current
72 if (naptime <= 0) {
73 print "alarm: time is in the past!" > "/dev/stderr"
74 exit 1
75 }
76 # zzzzzz..... go away if interrupted
77 if (system(sprintf("sleep %d", naptime)) != 0)
78 exit 1
79
80 # time to notify!
81 command = sprintf("sleep %d", delay)
82 for (i = 1; i <= count; i++) {
83 print message
84 # if sleep command interrupted, go away
85 if (system(command) != 0)
86 break
87 }
88
89 exit 0
90 }