#include <glib.h>
#include <gio/gio.h>
#include <string.h>

void
usage (char *invoked_program)
{
  g_print ("Usage: %s <path FILENAME | uri URI>\n", invoked_program);
  g_print ("Runs default handler for file FILENAME (if first argument is 'path')\n");
  g_print ("Runs default URI handler for uri URI (if first argument is 'uri')\n");
}

int
main (int argc, char **argv)
{
  GFile *gf;
  GAppInfo *ga;
  GList *gfs;
  GError *error;

  if (argc != 3)
  {
    usage (argv[0]);
    return 0;
  }

  if (strcmp (argv[1], "path") == 0)
  {
    gf = g_file_new_for_path (argv[2]);

    if (gf == NULL)
    {
      g_print ("failed to create a file for %s\n", argv[2]);
      return 1;
    }
    error = NULL;
    ga = g_file_query_default_handler (gf, NULL, &error);
    if (ga == NULL)
    {
      g_print ("failed to get default file handler for %s: %s\n", argv[2], error->message);
      return 1;
    }
    gfs = NULL;
    gfs = g_list_append (gfs, gf);
    if (!g_app_info_launch (ga, gfs, NULL, &error))
    {
      g_print ("failed to launch default file handler for %s: %s\n", argv[2], error->message);
      return 1;
    }
  }
  else if (strcmp (argv[1], "uri") == 0)
  {
    error = NULL;
    if (!g_app_info_launch_default_for_uri (argv[2], NULL, &error))
    {
      g_print ("failed to launch default uri handler for %s: %s\n", argv[2], error->message);
      return 1;
    }
  }
  else
  {
    usage (argv[0]);
  }
  return 0;
}
