#include <gtk/gtk.h>
#define SIT_VERSION "8 Jan 2013-patched"
gchar *incfiles="";

static void run(gpointer s){
   int pid;
   if (! (pid=g_spawn_command_line_async(s,NULL)) ) {
      gchar *buf=g_strdup_printf("for x in %s; do . $x; done ; %s",incfiles,(char *)s);
      pclose (popen(buf,"w"));
      g_free(buf);
   } else g_spawn_close_pid (pid);
}

static void leftclick(GtkStatusIcon *si, gpointer s){run(s);}
static void rightclick(GtkStatusIcon *si, guint b,guint a_t, gpointer s){run(s);}

/** refreshes the status icon image from file if it changes */
static void refresh(GFileMonitor *monitor, GFile *file, GFile *to_file, GFileMonitorEvent event, gpointer si){
   gtk_status_icon_set_from_file(si,g_file_get_path(file));
}

/** gets a new mouse over tooltip from file if it changes */
static void updatetooltip(GFileMonitor *monitor,   GFile *file, GFile *to_file, GFileMonitorEvent event, gpointer si){
   gtk_status_icon_set_tooltip_markup(si, g_mapped_file_get_contents(g_mapped_file_new(g_file_get_path(file), FALSE, NULL)));
}

int main(int argc, char *argv[]){
   GtkStatusIcon *si;
   char i=1;
gtk_init (&argc, &argv);
if ((argc>1)&&(argv[i][0]=='-')&&(argv[i++][1]=='i')) incfiles=argv[i++];
if ( argc < i+1 ) {
   g_printerr(
   "sit " SIT_VERSION "\nusage: %s [-i files] image tooltip left-action right-action ...\n\n" \
   "  -i           full path to file(s) with shell functions to include\n" \
   "  image        full path to image file\n" \
   "  tooltip      full path to tooltip file or a \"quoted tooltip\"\n" \
   "  left-action  action to run when left mouse button is clicked\n" \
   "  right-action action to run when right mouse button is clicked\n\n" \
   ,argv[0]);
   return 1;
}
/** loop through icon, tooltip, click messages **/
while (i<argc){
/** status icon **/
if (g_file_test(argv[i], G_FILE_TEST_EXISTS)){
   si = gtk_status_icon_new_from_file(argv[i]);
   g_signal_connect(g_file_monitor_file(g_file_new_for_path(argv[i++]), G_FILE_MONITOR_NONE, FALSE, NULL),
      "changed", G_CALLBACK(refresh),(gpointer) si);
}else{
   g_printerr("error: could not stat file %s\n",argv[i]);
   return 2;
}
/** tooltip **/
if (g_file_test(argv[i], G_FILE_TEST_EXISTS)){
   gtk_status_icon_set_tooltip_markup(si, g_mapped_file_get_contents(g_mapped_file_new(argv[i], FALSE, NULL)));
   g_signal_connect(g_file_monitor_file(g_file_new_for_path(argv[i]), G_FILE_MONITOR_NONE, FALSE, NULL),
      "changed", G_CALLBACK(updatetooltip),(gpointer) si);
}else if (argv[i]!=NULL) gtk_status_icon_set_tooltip_markup(si, argv[i]);
++i;
/** left click action **/
if (argv[i]!=NULL) g_signal_connect(G_OBJECT(si), "activate", G_CALLBACK(leftclick),(gpointer) argv[i]);
++i;
/** right click action **/
if (argv[i]!=NULL) g_signal_connect(G_OBJECT(si), "popup-menu", G_CALLBACK(rightclick), (gpointer) argv[i]);
++i;
}
gtk_main();
return 0;
}
