/* IglooFTP - Graphical and User Friendly FTP Client.
 * Copyright (c) 1998-1999 Jean-Marc Jacquet. 
 * All rights reserved.
 * 
 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
 * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE
 *
 * IglooFTP Original Packages, information and support,  
 * can be obtained at :
 *                              http://www.littleigloo.org
 * 
 *
 */

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

#include "protos.h"




static void
save_session (void)
{
  FILE *out = NULL;
  FTPsession that_session;
  int file_handle;
  char tmp_filename[MPLEN];
  char spawn_tmp[MPLEN];

  that_session = this_session;
  getcwd (that_session.local_dir, sizeof (that_session.local_dir));

  strcpy (that_session.start_dir, this_session.cwd_dir);

  tmpnam (tmp_filename);
  file_handle = open (tmp_filename, O_CREAT | O_RDWR, RC_PERM);
  write (file_handle, &that_session, sizeof (FTPsession));
  close (file_handle);

  spaw_session_path (spawn_tmp);
  if ((out = fopen (spawn_tmp, "w")) != NULL)
    {
      fprintf (out, tmp_filename);
      fflush (out);
      fclose (out);
    }
}



char
load_session (void)
{
  FILE *in = NULL;
  int file_handle;
  char spawn_tmp[MPLEN];
  char tmp_filename[MPLEN];

  spaw_session_path (spawn_tmp);

  if ((in = fopen (spawn_tmp, "r")) == NULL)
    return FALSE;

  fgets (tmp_filename, sizeof (tmp_filename), in);
  fclose (in);
  unlink (spawn_tmp);

  if ((file_handle = open (tmp_filename, O_RDONLY, RC_PERM)) == -1)
    return FALSE;

  read (file_handle, &this_session, sizeof (FTPsession));
  close (file_handle);

  unlink (tmp_filename);

  return TRUE;
}



static void
new_session (char SPAWNED)
{
  char current_dir[MPLEN];
  char prg_arg[256];
  MEM0 (prg_arg);

  if (this_connexion.is_connected && SPAWNED)
    {
      strcpy (prg_arg, SPAWN_ARG);
      save_session ();
    }

  getcwd (current_dir, sizeof (current_dir));
  chdir (prg_start_dir);
  execute_program (prg_path, prg_arg);
  chdir (current_dir);
}

void
spawn_session_from_widget (GtkWidget * widget, gpointer data)
{
  new_session (TRUE);
}

void
new_session_from_widget (GtkWidget * widget, gpointer data)
{
  new_session (FALSE);
}

/* EOF */
