]> git.sur5r.net Git - i3/i3status/blob - i3status.c
Merge getting thermal zone temperature from atsutane, thanks!
[i3/i3status] / i3status.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3status – Generates a status line for dzen2 or wmii
5  *
6  *
7  * Copyright © 2008-2009 Michael Stapelberg and contributors
8  * Copyright © 2009 Thorsten Toepper <atsutane at freethoughts dot de>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * * Redistributions of source code must retain the above copyright notice, this
15  *   list of conditions and the following disclaimer.
16  *
17  * * Redistributions in binary form must reproduce the above copyright notice, this
18  *   list of conditions and the following disclaimer in the documentation and/or other
19  *   materials provided with the distribution.
20  *
21  * * Neither the name of Michael Stapelberg nor the names of contributors
22  *   may be used to endorse or promote products derived from this software without
23  *   specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
26  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
28  * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
30  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
31  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
34  * DAMAGE.
35  *
36  */
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <fcntl.h>
40 #include <string.h>
41 #include <stdio.h>
42 #include <time.h>
43 #include <stdbool.h>
44 #include <stdarg.h>
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <limits.h>
48 #include <ctype.h>
49 #include <net/if.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
54 #include <glob.h>
55 #include <dirent.h>
56 #include <getopt.h>
57
58 #include "queue.h"
59
60 #ifdef LINUX
61 #include <linux/ethtool.h>
62 #include <linux/sockios.h>
63 #else
64 /* TODO: correctly check for *BSD */
65 #include <sys/param.h>
66 #include <sys/sysctl.h>
67 #include <sys/resource.h>
68 #endif
69
70 #include "i3status.h"
71
72 #define BAR "^fg(#333333)^p(5;-2)^ro(2)^p()^fg()^p(5)"
73
74 struct battery {
75         char *path;
76         /* Use last full capacity instead of design capacity */
77         bool use_last_full;
78         SIMPLEQ_ENTRY(battery) batteries;
79 };
80
81 SIMPLEQ_HEAD(battery_head, battery) batteries;
82
83 /* socket file descriptor for general purposes */
84 static int general_socket;
85
86 static const char *wlan_interface;
87 static const char *eth_interface;
88 static char *wmii_path;
89 static const char *time_format;
90 static bool use_colors;
91 static bool get_ethspeed;
92 static bool get_cpu_temperature;
93 static char *thermal_zone;
94 static const char *wmii_normcolors = "#222222 #333333";
95 static char order[MAX_ORDER][2];
96 static const char **run_watches;
97 static unsigned int num_run_watches;
98 static unsigned int interval = 1;
99
100 static int max(int a, int b) {
101         return (a > b ? a : b);
102 }
103
104 /*
105  * This function just concats two strings in place, it should only be used
106  * for concatting order to the name of a file or concatting color codes.
107  * Otherwise, the buffer size would have to be increased.
108  *
109  */
110 static char *concat(const char *str1, const char *str2) {
111         static char concatbuf[32];
112         (void)snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
113         return concatbuf;
114 }
115
116 /*
117  * Returns the correct color format for dzen (^fg(color)) or wmii (color <normcolors>)
118  *
119  */
120 static char *color(const char *colorstr) {
121         static char colorbuf[32];
122 #ifdef DZEN
123         (void)snprintf(colorbuf, sizeof(colorbuf), "^fg(%s)", colorstr);
124 #else
125         (void)snprintf(colorbuf, sizeof(colorbuf), "%s %s ", colorstr, wmii_normcolors);
126 #endif
127         return colorbuf;
128 }
129
130 /*
131  * Cleans wmii's /rbar directory by deleting all regular files
132  *
133  */
134 static void cleanup_rbar_dir() {
135 #ifdef DZEN
136         return;
137 #endif
138         struct dirent *ent;
139         DIR *dir;
140         char pathbuf[strlen(wmii_path)+256+1];
141
142         if ((dir = opendir(wmii_path)) == NULL)
143                 exit(EXIT_FAILURE);
144
145         while ((ent = readdir(dir)) != NULL) {
146                 if (ent->d_type == DT_REG) {
147                         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, ent->d_name);
148                         if (unlink(pathbuf) == -1)
149                                 exit(EXIT_FAILURE);
150                 }
151         }
152
153         (void)closedir(dir);
154 }
155
156 /*
157  * Creates the specified file in wmii's /rbar directory with
158  * correct modes and initializes colors if colormode is enabled
159  *
160  */
161 static void create_file(const char *name) {
162 #ifdef DZEN
163         return;
164 #endif
165         char pathbuf[strlen(wmii_path)+256+1];
166         int fd;
167         int flags = O_CREAT | O_WRONLY;
168         struct stat statbuf;
169
170         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
171
172         /* Overwrite file's contents if it exists */
173         if (stat(pathbuf, &statbuf) >= 0)
174                 flags |= O_TRUNC;
175
176         if ((fd = open(pathbuf, flags, S_IRUSR | S_IWUSR)) < 0)
177                 exit(EXIT_FAILURE);
178         if (use_colors) {
179                 char *tmp = color("#888888");
180                 if (write(fd, tmp, strlen(tmp)) != (ssize_t)strlen(tmp))
181                         exit(EXIT_FAILURE);
182         }
183         (void)close(fd);
184 }
185
186 /*
187  * Waits until wmii_path/rbar exists (= the filesystem gets mounted),
188  * cleans up all files and creates the needed files
189  *
190  */
191 static void setup(void) {
192         unsigned int i;
193         char pathbuf[512];
194
195 #ifndef DZEN
196         struct stat statbuf;
197         /* Wait until wmii_path/rbar exists */
198         for (; stat(wmii_path, &statbuf) < 0; sleep(interval));
199 #endif
200
201         cleanup_rbar_dir();
202         if (wlan_interface)
203                 create_file(concat(order[ORDER_WLAN],"wlan"));
204         if (eth_interface)
205                 create_file(concat(order[ORDER_ETH],"eth"));
206         if (get_cpu_temperature)
207                 create_file(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"));
208         create_file(concat(order[ORDER_LOAD],"load"));
209         if (time_format)
210                 create_file(concat(order[ORDER_TIME],"time"));
211         for (i = 0; i < num_run_watches; i += 2) {
212                 snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
213                 create_file(pathbuf);
214         }
215 }
216
217 /*
218  * Writes the given message in the corresponding file in wmii's /rbar directory
219  *
220  */
221 static void write_to_statusbar(const char *name, const char *message, bool final_entry) {
222 #ifdef DZEN
223         if (final_entry) {
224                 (void)printf("%s^p(6)\n", message);
225                 fflush(stdout);
226                 return;
227         }
228         (void)printf("%s" BAR, message);
229         return;
230 #endif
231
232         char pathbuf[strlen(wmii_path)+256+1];
233         int fd;
234
235         (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s", wmii_path, name);
236         if ((fd = open(pathbuf, O_RDWR)) == -1) {
237                 /* Try to re-setup stuff and just continue */
238                 setup();
239                 return;
240         }
241         if (write(fd, message, strlen(message)) != (ssize_t)strlen(message))
242                 exit(EXIT_FAILURE);
243         (void)close(fd);
244 }
245
246 /*
247  * Writes an errormessage to statusbar
248  *
249  */
250 static void write_error_to_statusbar(const char *message) {
251         cleanup_rbar_dir();
252         create_file("error");
253         write_to_statusbar("error", message, true);
254 }
255
256 /*
257  * Write errormessage to statusbar and exit
258  *
259  */
260 void die(const char *fmt, ...) {
261         char buffer[512];
262         va_list ap;
263         va_start(ap, fmt);
264         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
265         va_end(ap);
266
267         if (wmii_path != NULL)
268                 write_error_to_statusbar(buffer);
269         else
270                 fprintf(stderr, "%s", buffer);
271         exit(EXIT_FAILURE);
272 }
273
274 /*
275  * Skip the given character for exactly 'amount' times, returns
276  * a pointer to the first non-'character' character in 'input'.
277  *
278  */
279 static char *skip_character(char *input, char character, int amount) {
280         char *walk;
281         size_t len = strlen(input);
282         int blanks = 0;
283
284         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
285                 if (*walk == character)
286                         blanks++;
287
288         return (walk == input ? walk : walk-1);
289 }
290
291 /*
292  * Get battery information from /sys. Note that it uses the design capacity to
293  * calculate the percentage, not the last full capacity, so you can see how
294  * worn off your battery is.
295  *
296  */
297 static char *get_battery_info(struct battery *bat) {
298         char buf[1024];
299         static char part[512];
300         char *walk, *last;
301         int fd;
302         int full_design = -1,
303             remaining = -1,
304             present_rate = -1;
305         charging_status_t status = CS_DISCHARGING;
306
307         if ((fd = open(bat->path, O_RDONLY)) == -1)
308                 return "No battery found";
309
310         memset(part, 0, sizeof(part));
311         (void)read(fd, buf, sizeof(buf));
312         for (walk = buf, last = buf; (walk-buf) < 1024; walk++) {
313                 if (*walk == '\n') {
314                         last = walk+1;
315                         continue;
316                 }
317
318                 if (*walk != '=')
319                         continue;
320
321                 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW") ||
322                     BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW"))
323                         remaining = atoi(walk+1);
324                 else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
325                         present_rate = atoi(walk+1);
326                 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
327                         status = CS_CHARGING;
328                 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
329                         status = CS_FULL;
330                 else {
331                         /* The only thing left is the full capacity */
332                         if (bat->use_last_full) {
333                                 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
334                                     !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
335                                         continue;
336                         } else {
337                                 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
338                                     !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
339                                         continue;
340                         }
341
342                         full_design = atoi(walk+1);
343                 }
344         }
345         (void)close(fd);
346
347         if ((full_design == 1) || (remaining == -1))
348                 return part;
349
350         if (present_rate > 0) {
351                 float remaining_time;
352                 int seconds, hours, minutes;
353                 if (status == CS_CHARGING)
354                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
355                 else if (status == CS_DISCHARGING)
356                         remaining_time = ((float)remaining / (float)present_rate);
357                 else remaining_time = 0;
358
359                 seconds = (int)(remaining_time * 3600.0);
360                 hours = seconds / 3600;
361                 seconds -= (hours * 3600);
362                 minutes = seconds / 60;
363                 seconds -= (minutes * 60);
364
365                 (void)snprintf(part, sizeof(part), "%s %.02f%% %02d:%02d:%02d",
366                         (status == CS_CHARGING ? "CHR" :
367                          (status == CS_DISCHARGING ? "BAT" : "FULL")),
368                         (((float)remaining / (float)full_design) * 100),
369                         max(hours, 0), max(minutes, 0), max(seconds, 0));
370         } else {
371                 (void)snprintf(part, sizeof(part), "%s %.02f%%",
372                         (status == CS_CHARGING ? "CHR" :
373                          (status == CS_DISCHARGING ? "BAT" : "FULL")),
374                         (((float)remaining / (float)full_design) * 100));
375         }
376         return part;
377 }
378
379 /*
380  * Return the IP address for the given interface or "no IP" if the
381  * interface is up and running but hasn't got an IP address yet
382  *
383  */
384 static const char *get_ip_address(const char *interface) {
385         static char part[512];
386         struct ifreq ifr;
387         struct sockaddr_in addr;
388         socklen_t len = sizeof(struct sockaddr_in);
389         memset(part, 0, sizeof(part));
390
391         /* First check if the interface is running */
392         (void)strcpy(ifr.ifr_name, interface);
393         if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 ||
394             !(ifr.ifr_flags & IFF_RUNNING))
395                 return NULL;
396
397         /* Interface is up, get the IP address */
398         (void)strcpy(ifr.ifr_name, interface);
399         ifr.ifr_addr.sa_family = AF_INET;
400         if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
401                 return "no IP";
402
403         memcpy(&addr, &ifr.ifr_addr, len);
404         (void)inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, len);
405         if (strlen(part) == 0)
406                 (void)snprintf(part, sizeof(part), "no IP");
407
408         return part;
409 }
410
411 /*
412  * Just parses /proc/net/wireless looking for lines beginning with
413  * wlan_interface, extracting the quality of the link and adding the
414  * current IP address of wlan_interface.
415  *
416  */
417 static char *get_wireless_info() {
418         char buf[1024];
419         static char part[512];
420         char *interfaces;
421         int fd;
422         memset(buf, 0, sizeof(buf));
423         memset(part, 0, sizeof(part));
424
425         if ((fd = open("/proc/net/wireless", O_RDONLY)) == -1)
426                 die("Could not open /proc/net/wireless\n");
427         (void)read(fd, buf, sizeof(buf));
428         (void)close(fd);
429
430         interfaces = skip_character(buf, '\n', 1) + 1;
431         while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
432                 while (isspace((int)*interfaces))
433                         interfaces++;
434                 if (!BEGINS_WITH(interfaces, wlan_interface))
435                         continue;
436                 int quality;
437                 if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
438                         continue;
439                 if ((quality == UCHAR_MAX) || (quality == 0)) {
440                         if (use_colors)
441                                 (void)snprintf(part, sizeof(part), "%sW: down", color("#FF0000"));
442                         else (void)snprintf(part, sizeof(part), "W: down");
443                 } else (void)snprintf(part, sizeof(part), "%sW: (%03d%%) %s",
444                                 color("#00FF00"), quality, get_ip_address(wlan_interface));
445                 return part;
446         }
447
448         return part;
449 }
450
451 /*
452  * Combines ethernet IP addresses and speed (if requested) for displaying
453  *
454  */
455 static char *get_eth_info() {
456         static char part[512];
457         const char *ip_address = get_ip_address(eth_interface);
458         int ethspeed = 0;
459
460         if (get_ethspeed) {
461 #ifdef LINUX
462                 /* This code path requires root privileges */
463                 struct ifreq ifr;
464                 struct ethtool_cmd ecmd;
465
466                 ecmd.cmd = ETHTOOL_GSET;
467                 (void)memset(&ifr, 0, sizeof(ifr));
468                 ifr.ifr_data = (caddr_t)&ecmd;
469                 (void)strcpy(ifr.ifr_name, eth_interface);
470                 if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0)
471                         ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed);
472                 else get_ethspeed = false;
473 #endif
474         }
475
476         if (ip_address == NULL)
477                 (void)snprintf(part, sizeof(part), "E: down");
478         else {
479                 if (get_ethspeed)
480                         (void)snprintf(part, sizeof(part), "E: %s (%d Mbit/s)", ip_address, ethspeed);
481                 else (void)snprintf(part, sizeof(part), "E: %s", ip_address);
482         }
483
484         return part;
485 }
486
487 /*
488  * Reads the CPU temperature from /sys/class/thermal/thermal_zone0/temp and
489  * returns the temperature in degree celcius.
490  *
491  */
492 static char *get_cpu_temperature_info() {
493         static char part[16];
494         char buf[16];
495         int temp;
496         int fd;
497
498         memset(buf, 0, sizeof(buf));
499         memset(part, 0, sizeof(part));
500
501         if ((fd = open(thermal_zone, O_RDONLY)) == -1)
502                 die("Could not open %s\n", thermal_zone);
503         (void)read(fd, buf, sizeof(buf));
504         (void)close(fd);
505
506         if (sscanf(buf, "%d", &temp) != 1)
507                 (void)snprintf(part, sizeof(part), "T: ? C");
508         else
509                 (void)snprintf(part, sizeof(part), "T: %d C", (temp/1000));
510
511         return part;
512 }
513
514 /*
515  * Checks if the PID in path is still valid by checking:
516  *  (Linux) if /proc/<pid> exists
517  *  (NetBSD) if sysctl returns process infos for this pid
518  *
519  */
520 static bool process_runs(const char *path) {
521         char pidbuf[16];
522         static glob_t globbuf;
523         int fd;
524         memset(pidbuf, 0, sizeof(pidbuf));
525
526         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
527                 die("glob() failed\n");
528         fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
529         globfree(&globbuf);
530         if (fd < 0)
531                 return false;
532         (void)read(fd, pidbuf, sizeof(pidbuf));
533         (void)close(fd);
534
535 #ifdef LINUX
536         struct stat statbuf;
537         char procbuf[512];
538         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
539         return (stat(procbuf, &statbuf) >= 0);
540 #else
541         /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
542         struct kinfo_proc info;
543         size_t length = sizeof(struct kinfo_proc);
544         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
545         if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
546                 return false;
547         return (length != 0);
548 #endif
549 }
550
551 /*
552  * Reads the configuration from the given file
553  *
554  */
555 static int load_configuration(const char *configfile) {
556         #define OPT(x) else if (strcasecmp(dest_name, x) == 0)
557
558         /* check if the file exists */
559         struct stat buf;
560         if (stat(configfile, &buf) < 0)
561                 return -1;
562
563         int result = 0;
564         FILE *handle = fopen(configfile, "r");
565         if (handle == NULL)
566                 die("Could not open configfile\n");
567         char dest_name[512], dest_value[512], whole_buffer[1026];
568
569         while (!feof(handle)) {
570                 char *ret;
571                 if ((ret = fgets(whole_buffer, 1024, handle)) == whole_buffer) {
572                         /* sscanf implicitly strips whitespace */
573                         if (sscanf(whole_buffer, "%s %[^\n]", dest_name, dest_value) < 1)
574                                 continue;
575                 } else if (ret != NULL)
576                         die("Could not read line in configuration file\n");
577
578                 /* skip comments and empty lines */
579                 if (dest_name[0] == '#' || strlen(dest_name) < 3)
580                         continue;
581
582                 OPT("wlan")
583                         wlan_interface = strdup(dest_value);
584                 OPT("eth")
585                         eth_interface = strdup(dest_value);
586                 OPT("time_format")
587                         time_format = strdup(dest_value);
588                 OPT("battery") {
589                         struct battery *new = calloc(1, sizeof(struct battery));
590                         if (new == NULL)
591                                 die("Could not allocate memory\n");
592                         if (asprintf(&(new->path), "/sys/class/power_supply/BAT%d/uevent", atoi(dest_value)) == -1)
593                                 die("Could not build battery path\n");
594
595                         /* check if flags were specified for this battery */
596                         if (strstr(dest_value, ",") != NULL) {
597                                 char *flags = strstr(dest_value, ",");
598                                 flags++;
599                                 if (*flags == 'f')
600                                         new->use_last_full = true;
601                         }
602                         SIMPLEQ_INSERT_TAIL(&batteries, new, batteries);
603                 } OPT("color")
604                         use_colors = true;
605                 OPT("get_ethspeed")
606                         get_ethspeed = true;
607                 OPT("get_cpu_temperature") {
608                         get_cpu_temperature = true;
609                         if (strlen(dest_value) > 0) {
610                                 if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone%d/temp", atoi(dest_value)) == -1)
611                                         die("Could not build thermal_zone path\n");
612                         } else {
613                                  if (asprintf(&thermal_zone, "/sys/class/thermal/thermal_zone0/temp") == -1)
614                                         die("Could not build thermal_zone path\n");
615                         }
616                 } OPT("normcolors")
617                         wmii_normcolors = strdup(dest_value);
618                 OPT("interval")
619                         interval = atoi(dest_value);
620                 OPT("wmii_path")
621                 {
622 #ifndef DZEN
623                         static glob_t globbuf;
624                         struct stat stbuf;
625                         if (glob(dest_value, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
626                                 die("glob() failed\n");
627                         wmii_path = strdup(globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : dest_value);
628                         globfree(&globbuf);
629
630                         if ((stat(wmii_path, &stbuf)) == -1) {
631                                 fprintf(stderr, "Warning: wmii_path contains an invalid path\n");
632                                 free(wmii_path);
633                                 wmii_path = strdup(dest_value);
634                         }
635                         if (wmii_path[strlen(wmii_path)-1] != '/')
636                                 die("wmii_path is not terminated by /\n");
637 #endif
638                 }
639                 OPT("run_watch")
640                 {
641                         char *name = strdup(dest_value);
642                         char *path = name;
643                         while (*path != ' ')
644                                 path++;
645                         *(path++) = '\0';
646                         num_run_watches += 2;
647                         run_watches = realloc(run_watches, sizeof(char*) * num_run_watches);
648                         run_watches[num_run_watches-2] = name;
649                         run_watches[num_run_watches-1] = path;
650                 }
651                 OPT("order")
652                 {
653                         #define SET_ORDER(opt, idx) { if (strcasecmp(token, opt) == 0) sprintf(order[idx], "%d", c++); }
654                         char *walk, *token;
655                         int c = 0;
656                         walk = token = dest_value;
657                         while (*walk != '\0') {
658                                 while ((*walk != ',') && (*walk != '\0'))
659                                         walk++;
660                                 *(walk++) = '\0';
661                                 SET_ORDER("run", ORDER_RUN);
662                                 SET_ORDER("wlan", ORDER_WLAN);
663                                 SET_ORDER("eth", ORDER_ETH);
664                                 SET_ORDER("battery", ORDER_BATTERY);
665                                 SET_ORDER("cpu_temperature", ORDER_CPU_TEMPERATURE);
666                                 SET_ORDER("load", ORDER_LOAD);
667                                 SET_ORDER("time", ORDER_TIME);
668                                 token = walk;
669                                 while (isspace((int)(*token)))
670                                         token++;
671                         }
672                 }
673                 else
674                 {
675                         result = -2;
676                         die("Unknown configfile option: %s\n", dest_name);
677                 }
678         }
679         fclose(handle);
680
681 #ifndef DZEN
682         if (wmii_path == NULL)
683                 exit(EXIT_FAILURE);
684 #endif
685
686         return result;
687 }
688
689 int main(int argc, char *argv[]) {
690         char part[512],
691              pathbuf[512];
692         unsigned int i;
693
694         char *configfile = PREFIX "/etc/i3status.conf";
695         int o, option_index = 0;
696         struct option long_options[] = {
697                 {"config", required_argument, 0, 'c'},
698                 {"help", no_argument, 0, 'h'},
699                 {0, 0, 0, 0}
700         };
701
702         SIMPLEQ_INIT(&batteries);
703
704         while ((o = getopt_long(argc, argv, "c:h", long_options, &option_index)) != -1)
705                 if ((char)o == 'c')
706                         configfile = optarg;
707                 else if ((char)o == 'h') {
708                         printf("i3status (c) 2008-2009 Michael Stapelberg\n"
709                                 "Syntax: %s [-c <configfile>]\n", argv[0]);
710                         return 0;
711                 }
712
713         if (load_configuration(configfile) < 0)
714                 return EXIT_FAILURE;
715
716         setup();
717
718         if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
719                 die("Could not create socket\n");
720
721         while (1) {
722                 for (i = 0; i < num_run_watches; i += 2) {
723                         bool running = process_runs(run_watches[i+1]);
724                         if (use_colors)
725                                 snprintf(part, sizeof(part), "%s%s: %s",
726                                         (running ? color("#00FF00") : color("#FF0000")),
727                                         run_watches[i],
728                                         (running ? "yes" : "no"));
729                         else snprintf(part, sizeof(part), "%s: %s", run_watches[i], (running ? "yes" : "no"));
730                         snprintf(pathbuf, sizeof(pathbuf), "%s%s", order[ORDER_RUN], run_watches[i]);
731                         write_to_statusbar(pathbuf, part, false);
732                 }
733
734                 if (wlan_interface)
735                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info(), false);
736                 if (eth_interface)
737                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info(), false);
738                 struct battery *current_battery;
739                 SIMPLEQ_FOREACH(current_battery, &batteries, batteries) {
740                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info(current_battery), false);
741                 }
742                 if (get_cpu_temperature)
743                         write_to_statusbar(concat(order[ORDER_CPU_TEMPERATURE], "cpu_temperature"), get_cpu_temperature_info(), false);
744
745                 /* Get load */
746 #ifdef LINUX
747                 int load_avg;
748                 if ((load_avg = open("/proc/loadavg", O_RDONLY)) == -1)
749                         die("Could not open /proc/loadavg\n");
750                 (void)read(load_avg, part, sizeof(part));
751                 (void)close(load_avg);
752                 *skip_character(part, ' ', 3) = '\0';
753 #else
754                 /* TODO: correctly check for NetBSD, check if it works the same on *BSD */
755                 struct loadavg load;
756                 size_t length = sizeof(struct loadavg);
757                 int mib[2] = { CTL_VM, VM_LOADAVG };
758                 if (sysctl(mib, 2, &load, &length, NULL, 0) < 0)
759                         die("Could not sysctl({ CTL_VM, VM_LOADAVG })\n");
760                 double scale = load.fscale;
761                 (void)snprintf(part, sizeof(part), "%.02f %.02f %.02f",
762                                 (double)load.ldavg[0] / scale,
763                                 (double)load.ldavg[1] / scale,
764                                 (double)load.ldavg[2] / scale);
765 #endif
766                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part, !time_format);
767
768                 if (time_format) {
769                         /* Get date & time */
770                         time_t current_time = time(NULL);
771                         struct tm *current_tm = localtime(&current_time);
772                         (void)strftime(part, sizeof(part), time_format, current_tm);
773                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part, true);
774                 }
775
776                 sleep(interval);
777         }
778 }