//-----------------------------------------------------------
// Copyright Christian Arnault LAL-Orsay CNRS
// arnault@lal.in2p3.fr
// See the complete license in cmt_license.txt "http://www.cecill.info". 
//-----------------------------------------------------------

#include "cmt_std.h"
#include "cmt_lock.h"
#include "cmt_system.h"
#include "cmt_error.h"
#include "cmt_symbol.h"

//----------------------------------------------------------
CmtLock::status CmtLock::lock ()
{
  status s = check ();

  switch (s)
    {
    case locked_by_user:
      cout << "Package already locked by you" << endl;
      return (s);
    case locked_by_another_user:
      CmtError::set (CmtError::cannot_lock, "lock> Package already locked by another user");
      return (s);
    case not_locked:
      break;
    }

  cmt_string text = "locked by ";
  text += CmtSystem::user ();
  text += " date ";
  text += CmtSystem::now ();

  if (!text.write ("lock.cmt"))
    {
      CmtError::set (CmtError::cannot_write_lock, "lock>");
      return (still_unlocked);
    }

  Symbol* lock_command = Symbol::find ("lock_command");
  if (lock_command != 0)
    {
      cmt_string command = lock_command->build_macro_value ();

      if (command != "")
	{
	  if (CmtSystem::execute (command) != 0)
	    {
	      CmtError::set (CmtError::cannot_run_lock_command, "lock>");
	      return (still_unlocked);
	    }
	}
    }

  cout << "Package now locked" << endl;

  return (locked_by_user);
}

//----------------------------------------------------------
CmtLock::status CmtLock::unlock ()
{
  status s = check ();

  switch (s)
    {
    case locked_by_user:
      break;
    case locked_by_another_user:
      CmtError::set (CmtError::cannot_unlock, "unlock> Package locked by another user");
      return (s);
    case not_locked:
      cout << "The package was not locked" << endl;
      return (s);
    }

  Symbol* unlock_command = Symbol::find ("unlock_command");
  if (unlock_command != 0)
    {
      cmt_string command = unlock_command->build_macro_value ();

      if (command != "")
	{
	  if (CmtSystem::execute (command) != 0)
	    {
	      CmtError::set (CmtError::cannot_run_unlock_command, "unlock>");
	      return (still_locked);
	    }
	}
    }

  if (!CmtSystem::remove_file ("lock.cmt"))
    {
      CmtError::set (CmtError::cannot_remove_lock, "unlock>");
      return (still_locked);
    }

  cout << "Package now unlocked" << endl;

  return (not_locked);
}

//----------------------------------------------------------
CmtLock::status CmtLock::check ()
{
  cmt_string me = CmtSystem::user ();
  cmt_string text;

  if (text.read ("lock.cmt"))
    {
      CmtSystem::cmt_string_vector words;

      CmtSystem::split (text, " ", words);

      if (words.size () >= 3)
	{
	  if (words[2] == me)
	    {
	      return (locked_by_user);
	    }
	  else
	    {
	      return (locked_by_another_user);
	    }
	}
    }
	
  return (not_locked);
}
