/***************************************************************************
 *   Copyright (C) 2003 by Mattia Merzi                                    *
 *   ottobit@ferrara.linux.it                                              *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <kprocess.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <qmessagebox.h>
#include <stdlib.h>

#include <kcmdlineargs.h>

#include "KBlueLockHandleProcess.h"


KBlueLockHandleProcess* KBlueLockHandleProcess::_instance = 0;

KBlueLockHandleProcess* KBlueLockHandleProcess::getDefaultProcess()
{
    kdDebug() << "init" << endl;
    if (_instance == 0) {
        _instance = new KBlueLockHandleProcess();
    }
    return _instance;
}

KBlueLockHandleProcess::KBlueLockHandleProcess()
{
  kdDebug() << "KBlueLockHandleProcess" << endl;
  proc = new KProcess();
  connect(proc, SIGNAL(processExited(KProcess *)),this,
    SLOT(kdesktop_lock_terminated()));

  QString path = getenv("PATH");
  path.append(":/usr/sbin:/sbin");

  QString target_app = "kdesktop_lock";
  if(!qstrcmp(KCmdLineArgs::appName(),"kdesktop_lock")) {
    target_app = "kdesktop_lock_nobt";
  }
  kdesktop_lock = KGlobal::dirs()->findExe(target_app, path);
  kdDebug() << "target_app: " << target_app << endl;
  kdDebug() << "kdesktop_lock: " << kdesktop_lock << endl;
  if (kdesktop_lock.isEmpty()) {
    QMessageBox::critical(NULL,"Ooops !",
      "Cannot find " + target_app + ".\nIs " + target_app + " in your $PATH ?"
     ,"Ok");
    exit(-1);
  } else {
    *proc << kdesktop_lock;
  }
}

void KBlueLockHandleProcess::setParams(int force,int nolock) {
  if (force) *proc << "--forcelock";
  if (nolock) *proc << "--dontlock";
}

void KBlueLockHandleProcess::start() {
  bool result = proc->start(KProcess::NotifyOnExit , KProcess::All);
  if(!result){
    QMessageBox::critical(NULL,"Ooops !",
      "Cannot start kdesktop_lock !!!","damn ...");
    exit(-1);
  } else {
    kdDebug() << "process started ..." << endl;
  }
}

void KBlueLockHandleProcess::terminate() {
  proc->kill(SIGTERM);
}

void KBlueLockHandleProcess::kdesktop_lock_terminated() {
  kdDebug() << "kdesktop_lock terminated.\nExiting ..." << endl;
  exit(0);
}

KBlueLockHandleProcess::~KBlueLockHandleProcess()
{
}

#include "KBlueLockHandleProcess.moc"
