//////////////////////////////////////////////////////////////
//      $Id: debAptInterface.cpp,v 1.32.2.1 2002/12/13 15:20:21 toivo Exp $
//
// Author: Toivo Pedaste
//
#include "../config.h"
#include <stdlib.h>

#include "klocale.h"
#include <kaction.h>
#include <kstdaction.h>

#include "kpackage.h"
#include "updateLoc.h"
#include "debAptInterface.h"
#include "cache.h"
#include "pkgOptions.h"



//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

DEBAPT::DEBAPT():DEB()
{
  head = "DEBAPT";
  name = i18n("APT: Debian");

  queryMsg = i18n("Querying DEB APT package list: ");
  procMsg = i18n("Kpackage: Waiting on APT-GET");

  hasRemote = TRUE;

  locatedialog = new Locations(i18n("Location of Debian Packages"));

  locatedialog->dLocations(1, 8, this, i18n("D"),
			   "Deb", "*.deb",
			   i18n("Location of Directories Containing Debian Packages"));
  connect(locatedialog,SIGNAL(returnVal(LcacheObj *)),
	  this,SLOT(setAvail(LcacheObj *)));
  locatedialog->apply_slot();

  paramsInst.append(new param(i18n("Download only"),FALSE,FALSE,"-d"));
  paramsInst.append(new param(i18n("No download"),FALSE,FALSE,"--no-download"));
  paramsInst.append(new param(i18n("Ignore missing"),FALSE,FALSE,"-m"));
  paramsInst.append(new param(i18n("Ignore hold"),FALSE,FALSE,"--ignore-hold"));
  paramsInst.append(new param(i18n("Assume yes"),TRUE,FALSE,"--yes"));
  paramsInst.append(new param(i18n("Test (do not uninstall)"),FALSE,FALSE,"-s"));

  paramsUninst.append(new param(i18n("Purge Config Files"),FALSE,FALSE,"--purge"));
  paramsUninst.append(new param(i18n("Assume yes"),TRUE,FALSE,"--yes"));
  paramsUninst.append(new param(i18n("Test (do not uninstall)"),FALSE,FALSE,"-s"));

  env = "DEBIAN_FRONTEND=readline; export DEBIAN_FRONTEND; ";

  noFetch = TRUE;
}

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
DEBAPT::~DEBAPT()
{
}

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

bool DEBAPT::isType(char *, const QString &)
{
  return false;
}

void DEBAPT::makeMenu(KAccel *keys, KActionCollection* act)
{
  updateM = new KAction( i18n("&Update"), QString::null,
			 0, this,
			 SLOT(updateS()), act, "debapt_update");
  updateM->plugAccel(keys);
  upgradeM = new KAction( i18n("U&pgrade"), QString::null,
			  0, this,
			  SLOT(upgradeS()), act, "debapt_upgrade");
  upgradeM->plugAccel(keys);
  fixupM = new KAction( i18n("&Fixup"), QString::null,
			 0, this,
			 SLOT(fixupS()), act, "debapt_fixup");
  fixupM->plugAccel(keys);
}

void DEBAPT::setMenu(KActionCollection*, bool enable)
{
  updateM->setEnabled(enable);
  upgradeM->setEnabled(enable);
  fixupM->setEnabled(enable);
}

void DEBAPT::updateS()
{
 kprun->run("apt-get update", "APT update");
 if (kprun->exec())
   kpackage->management->collectData(TRUE);
 }

void DEBAPT::upgradeS()
{
 kprun->run(env + "apt-get upgrade", "APT upgrade");
 if (kprun->exec())
   kpackage->management->collectData(TRUE);
 }

void DEBAPT::fixupS()
{
 kprun->run(env + "apt-get -f install", "APT fixup");
 if (kprun->exec())
   kpackage->management->collectData(TRUE);
}

void DEBAPT::listPackages(QPtrList<packageInfo> *pki)
{
  if (hostName.isEmpty()) {
    listInstalledPackages(pki);
  } else {
    listRemotePackages(pki);
  }
  listAvail(pki);
  if (hostName.isEmpty() && packageLoc) {
    listUnIPackages(pki, packageLoc);
  }
}

void DEBAPT::listRemotePackages(QPtrList<packageInfo> *pki)
{
  listRPack(pki);
}

void DEBAPT::listRPack(QPtrList<packageInfo> *pki)
{
  int NLINES =  70000;

  packageInfo *p;
  QStringList  plist;

  kpackage->setStatus(i18n("Querying DEB APT remote package list: %1").arg(hostName));
  kpackage->setPercent(0);

  QString cmd = "cat ";
  cmd += STATUS;

  QStringList list = kpty->run(cmd);
  kpackage->setStatus(i18n("Processing DEB APT remote package list: %1").arg(hostName));
  //  kdDebug() << "P=" << list.count() <<"\n";
  kpackage->setPercent(50);


  if (list.count() > 0) {

    QString s;

    kpackage->setPercent(50 );

    int cnt = 0;
    for ( QStringList::Iterator it = list.begin();  it != list.end(); ++it ) {
      cnt++;
      if (cnt % (NLINES/20) == 0) {
	kpackage->setPercent(((cnt * 100)/ NLINES ) + 50);
	//	kdDebug() << cnt << "_" << ((cnt * 100) / NLINES) <<"\n";
      }

      if (!(*it).isEmpty()) {
	s = *it;
	//	kdDebug() << s.length() << "<" << s << ">\n";
	plist << s;
      } else {
	//	kdDebug() << "---------\n";
	p = collectInfo(plist);
	if (p) {
	  if (!p->pkgInsert(pki, typeID, TRUE)) {
	    delete p;
	  }
	}
	plist.clear();
      }
    }
  }

  list.clear();
  kpackage->setStatus(i18n("DEB APT"));
  kpackage->setPercent(100);
}

void DEBAPT::listAvail(QPtrList<packageInfo> *pki)
{
  int NLINES =  150000;

  packageInfo *p;
  QStringList  plist;

  kdDebug() << "H=" << hostName << "\n";
  if (hostName.isEmpty())
    kpackage->setStatus(i18n("Querying DEB APT available list"));
  else
    kpackage->setStatus(i18n("Querying DEB APT available list: %1").arg(hostName));
  kpackage->setPercent(0);

  QStringList list = kpty->run("apt-cache dumpavail");
  if (hostName.isEmpty())
    kpackage->setStatus(i18n("Processing DEB APT available list"));
  else
     kpackage->setStatus(i18n("Processing DEB APT available list: %1").arg(hostName));

  kdDebug() << "A=" << list.count() <<"\n";
  kpackage->setPercent(50);

  if (list.count() > 0) {

    QString s;

    kpackage->setPercent(50 );

    int cnt = 0;
    for ( QStringList::Iterator it = list.begin();  it != list.end(); ++it ) {
      cnt++;
      if (cnt % (NLINES/20) == 0) {
	kpackage->setPercent(((cnt * 100)/ NLINES ) + 50);
	//	kdDebug() << cnt << "_" << ((cnt * 100) / NLINES) <<"\n";
      }

      if (!(*it).isEmpty()) {
	s = *it;
	//	kdDebug() << s.length() << "<" << s << ">\n";
	plist << s;
      } else {
	p = collectInfo(plist);
	if (p) {
	  //	kdDebug() << "yyyyyyX" << "\n";
	  if (!p->pkgInsert(pki, typeID, FALSE)) {
	    delete p;
	  }
	}
	plist.clear();
      }
    }
  }

  list.clear();
  kpackage->setStatus(i18n("DEB APT"));
  kpackage->setPercent(100);
}

QStringList  DEBAPT::listInstalls(QStringList packs, bool install)
{
  bool extras=FALSE, found=FALSE;

  QString match;
  QString s = "apt-get -s ";
  if (install) {
    s += "install ";
    match = " extra packages ";
  } else {
    match = "packages will be REMOVED:";
    s += "remove ";
  }

  for ( QStringList::Iterator it = packs.begin(); it != packs.end(); ++it ) {
    s +=  *it;
    s += " ";
  }

  QStringList list = kpty->run(s, TRUE, TRUE);
  //  kdDebug() << "LS=" << list.count()  << "\n";

  QString packAll;
  for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
    //        kdDebug() << "M=" << *it << "\n";
    if ((*it).find(match) >= 0 || extras) {
      if (extras) {
	if ((*it)[0] == ' ') {
	  packAll += *it;
	  found = true;
	} else {
	  break;
	}
      }
      extras=TRUE;
    }
  }

  if (!found) {
    QStringList nill;
    return nill;
  } else {
    QStringList plist = QStringList::split(' ',packAll);
    return plist;
  }
}

QStringList DEBAPT::getFileList(packageInfo *p)
{
  QString fn( p->getFilename());
  if(!fn.isEmpty())
    return getUFileList(fn);
  else {
    if (hostName.isEmpty())
      return getIFileList(p);
    else {
      if (p->packageState == packageInfo::INSTALLED) {
	return getRFileList(p);
      } else
	return "";
    }
  }
}

 QStringList DEBAPT::getRFileList(packageInfo *p)
{
  QString from;
  QString name = p->getProperty("name");

  from = "cat ";
  from += INFODIR;
  from += name;
  from += ".list";

  return kpty->run(from);
}

//////////////////////////////////////////////////////////////////////////////
QString DEBAPT::doUninstall(int uninstallFlags, QString packs, bool &test)
{
  QString s = env + "apt-get remove ";
  s += setOptions(uninstallFlags, paramsUninst);
  s +=  packs;

  kdDebug() << "uCMD=" << s << "\n";

  if (uninstallFlags>>2 & 1)
    test = TRUE;

  return s;
}

//////////////////////////////////////////////////////////////////////////////
QString DEBAPT::install(int installFlags, QPtrList<packageInfo> *p,
			      bool &test)
{
  QString packs = "";
  QString files = "";
  packageInfo *i;

  for (i = p->first(); i!= 0; i = p->next())  {
    QString file = i->getFilename();
    QString fname = i->fetchFilename();

    if (!file.isEmpty()) {
      files += "'";
      files += file;
      files += "'";
      files += " ";
    } else if (fname != "") {
      packs += "'";
      packs += fname;
      packs += "'";
      packs += " ";
    }
  }

  if (!files.isEmpty()) { // What if mixed?
    return DEB::doInstall(installFlags, files, test);
  } else {
    return doInstall(installFlags, packs, test);
  }
}

QString DEBAPT::doInstall(int installFlags, QString packs, bool &test)
{
  QString s = env + "apt-get install ";
  s += setOptions(installFlags, paramsInst);
  s +=  packs;

  kdDebug() << "iCMD=" << s << "\n";

  if ((installFlags>>0 & 1) || (installFlags>>5 & 1))
    test = TRUE;

  return s;
}

#include "debAptInterface.moc"
