#include <dirent.h>
#include <time.h>
#include <netinet/in.h>
+#include <getopt.h>
#include "nwho.h"
-static int is_uptime;
static time_t now;
struct out_host {
};
}
+static int
+cmp_users_by_hosts(const void *va, const void *vb)
+{
+ const struct out_user *a = va;
+ const struct out_user *b = vb;
+ return strcmp(a->host->name, b->host->name);
+}
+
+static int
+cmp_users_by_names(const void *va, const void *vb)
+{
+ const struct out_user *a = va;
+ const struct out_user *b = vb;
+ return strcmp(a->user->name, b->user->name);
+}
+
+static void
+sort_users(int by_hosts)
+{
+ qsort(user_array, num_users, sizeof(user_array[0]),
+ (by_hosts ? cmp_users_by_hosts : cmp_users_by_names));
+}
+
+static int
+cmp_hosts(const void *va, const void *vb)
+{
+ const struct out_host * const *a = va;
+ const struct out_host * const *b = vb;
+ return strcmp((*a)->name, (*b)->name);
+}
+
+static void
+sort_hosts(void)
+{
+ qsort(host_array, num_hosts, sizeof(host_array[0]), cmp_hosts);
+}
+
static void
puttime(int s)
{
closedir(d);
}
+static void
+usage(void)
+{
+ printf("\
+Usage: nwho <options>\n\
+ or: nuptime <options>\n\
+\n\
+Options:\n\
+-h Sort user list by hosts (default: by users)\n\
+-u Display host uptimes (default if called as `nuptime')\n\
+");
+ exit(0);
+}
+
int
main(int argc, char **argv)
{
printf("nwho " STRINGIFY(VERSION) "\n");
return 0;
}
+ if (argc == 2 && !strcmp(argv[1], "--help"))
+ usage();
+
+ int opt;
+ int uptime_mode = !!strstr(argv[0], "uptime");
+ int want_sort_by_hosts = 0;
- if (strstr(argv[0], "uptime"))
- is_uptime = 1;
- if (argc != 1)
+ while ((opt = getopt(argc, argv, "hu")) >= 0)
+ switch (opt)
+ {
+ case 'h':
+ want_sort_by_hosts = 1;
+ break;
+ case 'u':
+ uptime_mode = 1;
+ break;
+ default:
+ fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
+ exit(1);
+ }
+ if (optind < argc)
{
- fprintf(stderr, "Usage: %s\n", argv[0]);
- return 1;
+ fprintf(stderr, "This program does not need any arguments. Try `%s --help' for more information.\n", argv[0]);
+ exit(1);
}
now = time(NULL);
return 0;
}
- if (!is_uptime)
- show_users();
+ if (!uptime_mode)
+ {
+ sort_users(want_sort_by_hosts);
+ show_users();
+ }
else
- show_uptime();
+ {
+ sort_hosts();
+ show_uptime();
+ }
return 0;
}