#!/usr/bin/env slsh
% -*- slang -*-

static variable Confirm_Move = 0;

static define get_yn ()
{
   variable args = __pop_args (_NARGS);
   () = fprintf (stdout, __push_args (args));
   () = fflush (stdout);
   
   variable yn;
   if (fgets (&yn, stdin) <= 0)
     return -1;
   
   "y" == strlow (strtrim (yn));
}

   
static define move_file (from, to)
{
   if (from == to)
     {
	() = fprintf (stderr, "%s: Cannot move a file to itself.\n", __argv[0]);
	return -1;
     }

   if (0 == rename (from, to))
     return 0;

   variable st = stat_file (to);

   if (st != NULL)
     {
	if (1 != get_yn ("%s exists.  Overwrite? [y/n]", to))
	  {
	     () = fputs ("Not Confirmed\n", stdout);
	     return -1;
	  }
	() = remove (to);
     }
   
   if (0 == rename (from, to))
     return 0;

   ()=fprintf (stderr, "Failed to rename %s to %s: %s\n",
	       from, to, errno_string (errno));
   
   return -1;
}

define move_files (from_files, to)
{
   variable st = stat_file (to);
   if (st == NULL)
     {
	if (length (from_files) != 1)
	  {
	     () = fprintf (stderr, "%s must be a directory\n", to);
	     exit (1);
	  }
	if (-1 == move_file (from_files[0], to))
	  exit (1);
	exit (0);
     }
     
   !if (stat_is ("dir", st.st_mode))
     {
	if (length (from_files) != 1)
	  {
	     () = fprintf (stderr, "%s must be a directory\n", to);
	     exit (1);
	  }
	if (-1 == move_file (from_files[0], to))
	  exit (1);
	exit (0);
     }

   
   foreach (from_files)
     {
	variable old = ();
	variable new = path_concat (to, path_basename (old));
	
	if (NULL == stat_file (old))
	  {
	     () = fprintf (stderr, "Unable to access %s\n", old);
	     continue;
	  }

	if (Confirm_Move)
	  {
	     if (1 != get_yn ("Move %s to %s/? [y/n]", old, to))
	       {
		  () = fputs ("Not Confirmed\n", stdout);
		  continue;
	       }
	  }


	() = move_file (old, new);
     }
}

static define usage ()
{
   () = fprintf (stdout, "Usage: %s [-i]  files ... dir\n", __argv[0]);
   exit (1);
}

define main (argc, argv)
{
   argc--;
   argv = argv[[1:]];

   while (argc > 1)
     {
	if (argv[0] == "-i")
	  {
	     Confirm_Move = 1;
	     argc--;
	     argv = argv[[1:]];
	     continue;
	  }
	break;
     }
   
   if (argc < 2)
     usage ();

   move_files (argv[[0:argc-2]], argv[argc-1]);
}


define slsh_main ()
{
   main (__argc, __argv);
}


   
   
   
