#include <stdio.h>
#include <stdlib.h>

#include <glib.h>
#include <glib/gstdio.h>
#include "unity-webapps-application-info.h"
#include "unity-webapps-application-manifest.h"

static gboolean
write_desktop_file (UnityWebappsApplicationManifest *manifest)
{
  UnityWebappsApplicationInfo *info;
  const gchar *name, *domain;
  gchar *desktop_name;
  GError *error;
  
  name = unity_webapps_application_manifest_get_name (manifest);
  domain = unity_webapps_application_manifest_get_domain (manifest);

  if (!domain)
    return FALSE;

  info = unity_webapps_application_info_new (name, domain, "", NULL);

  // It's a waste of time to free this.
  desktop_name = unity_webapps_application_info_get_desktop_file_name (info);
  
  error = NULL;
  
  unity_webapps_application_info_write_desktop_file_to_path (info, desktop_name, &error);
  
  if (error != NULL)
    {
      // No reason to free
      g_warning ("Error writing desktop file: %s \n", error->message);
      return FALSE;
    }
    
  return TRUE;
}

gint
main (gint argc, gchar **argv)
{
  UnityWebappsApplicationManifest *manifest;
  gboolean wrote;


  g_type_init ();
  
  if (argc != 2)
    {
      g_printf("Usage: unity-webapps-desktop-file <<path to manifest.json>>\n");
      return 1;
    }
  
  manifest = unity_webapps_application_manifest_new_from_file (argv[1]);
  
  if (manifest == FALSE)
    {
      g_printf("Failed to load and parse manifest file \n");
      return 1;
    }
  
  wrote = write_desktop_file (manifest);
  
  if (wrote == FALSE)
    {
      g_printf("Failed to write desktop file \n");
      return 1;
    }

  return 0;
}
