1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#define FOR_hwclock
27#include "toys.h"
28#include <linux/rtc.h>
29
30GLOBALS(
31 char *f;
32)
33
34void hwclock_main()
35{
36 struct timezone tzone;
37 struct timeval timeval;
38 struct tm tm;
39 int fd = -1, utc;
40
41 if (FLAG(u)) utc = 1;
42 else if (FLAG(l)) utc = 0;
43 else utc = !readfile("/etc/adjtime", toybuf, sizeof(toybuf)) ||
44 !!strstr(toybuf, "UTC");
45
46 if (!FLAG(t)) {
47 if (!TT.f) TT.f = "/dev/rtc0";
48 fd = xopen(TT.f, O_WRONLY*FLAG(w));
49
50
51 if (!FLAG(w)) {
52 xioctl(fd, RTC_RD_TIME, &tm);
53 timeval.tv_sec = xmktime(&tm, utc);
54 timeval.tv_usec = 0;
55 }
56 }
57
58 if (FLAG(w) || FLAG(t)) {
59 if (gettimeofday(&timeval, 0)) perror_exit("gettimeofday failed");
60 if (!(utc ? gmtime_r : localtime_r)(&timeval.tv_sec, &tm))
61 error_exit(utc ? "gmtime_r failed" : "localtime_r failed");
62 }
63
64 if (FLAG(w)) {
65
66
67
68 tm.tm_isdst = 0;
69 xioctl(fd, RTC_SET_TIME, &tm);
70 } else if (FLAG(s)) {
71 tzone.tz_minuteswest = timezone / 60 - 60 * daylight;
72 } else if (FLAG(t)) {
73
74
75 tzone.tz_minuteswest = timezone / 60;
76 if (tm.tm_isdst) tzone.tz_minuteswest -= 60;
77 if (!utc) timeval.tv_sec += tzone.tz_minuteswest * 60;
78 } else {
79 strftime(toybuf, sizeof(toybuf), "%F %T%z", &tm);
80 xputs(toybuf);
81 }
82 if (FLAG(t) || FLAG(s)) {
83 tzone.tz_dsttime = 0;
84 if (settimeofday(&timeval, &tzone)) perror_exit("settimeofday failed");
85 }
86
87 xclose(fd);
88}
89