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

#include <glib.h>

#include "config.h"

#ifdef HAVE_SUFFICIENT_NSSYSTEMDIRECTORIES
#include <limits.h>
#include <NSSystemDirectories.h>
#include <string.h>
#include <wordexp.h>
#endif

static  gchar  **g_user_special_dirs = NULL;

#ifdef HAVE_SUFFICIENT_NSSYSTEMDIRECTORIES
static gchar *
find_folder (NSSearchPathDirectory type)
{
  char ns_path[PATH_MAX];

  NSSearchPathEnumerationState state = NSStartSearchPathEnumeration(type, NSUserDomainMask);
  if ((state = NSGetNextSearchPathEnumeration(state, ns_path)))
    {
      /*
	Can be a multidir list, but that's not what the GUserDirectory
	API uses, so just take first one (highest precedence).
      */

      /*
	ns_path often in user homedir and uses ~ for that. Avoid GFile
	because glib is below gio in stack.
      */

      if (ns_path[0] == '~')
	{
	  // need to expand homedir
	  char *subdir;
	  wordexp_t pwordexp;
	  GString *fullpath;

	  subdir = strstr(ns_path, "/");
	  if (subdir)
	    {
	      // truncate ns_path at slash, point subdir to after it
	      subdir[0] = '\0';
	      subdir++;
	    }

	  wordexp(ns_path, &pwordexp, 0);
	  fullpath = g_string_new(pwordexp.we_wordv[0]);
	  wordfree(&pwordexp);
	  if (subdir)
	    {
	      // reconstruct path with subdir
	      g_string_append(fullpath, "/");
	      g_string_append(fullpath, subdir);
	    }
	  return g_string_free(fullpath, FALSE);
	}
      else
	{
	  // there was no tilde in ns_path
	  return strdup(ns_path);
	}
    }
  return NULL;
}

static void
load_user_special_dirs (void)
{
  g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (NSDesktopDirectory);
  g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (NSDocumentDirectory);
  g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (NSDownloadsDirectory);
  g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (NSMusicDirectory);
  g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (NSPicturesDirectory);
  g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = find_folder (NSSharedPublicDirectory);
  g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
  g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (NSMoviesDirectory);
}
#else
#warning "fall back to some other method"
#endif

int main (void) { 
  int i;

  g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);

  load_user_special_dirs();

  for (i = 0; i < G_USER_N_DIRECTORIES; i++)
    {
      printf("%s\n", g_user_special_dirs[i]);
    }

  exit(0);
}
