#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <Imlib2.h>

#include "imlib2_common.h"
#include "loader.h"

int
load2(ImlibImage * im, int load_data)
{
   ImlibLoader        *loader;
   int                 res;
   const char         *s, *p, *q;
   char                tmp[] = "/tmp/imlib2_loader_gpg-XXXXXX";
   char               *real_ext, *dest;

   /* make sure this file ends in ".pgp" and that there's another ext
    * (e.g. "foo.png.pgp") */
   for (p = s = im->real_file, q = NULL; *s; s++)
     {
        if (*s != '.' && *s != '/')
           continue;
        q = p;
        p = s + 1;
     }
   if (!q || strcasecmp(p, "pgp"))
      return 0;

   if (!(real_ext = strndup(q, p - q - 1)))
      return 0;

   loader = __imlib_FindBestLoaderForFormat("jpg", 0);
   if (!loader)
      return 0;

   dest = mkstemp(tmp);
   close(dest);

   char result[500]; 
   strcpy(result, "gpg --decrypt --quiet ");
   strcat(result, im->real_file);
   strcat(result, " > ");
   strcat(result, tmp);

   system(result);

   res = __imlib_LoadEmbedded(loader, im, tmp, load_data);

 quit:
   unlink(tmp);

   return res;
}

void
formats(ImlibLoader * l)
{
   static const char  *const list_formats[] = { "pgp" };
   __imlib_LoaderSetFormats(l, list_formats,
                            sizeof(list_formats) / sizeof(char *));
}