#include <config.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <strings.h>
#include <kapp.h>
#include <time.h>

#include "rpmprot.h"

RpmProtocol::RpmProtocol(const char *localFile, const char *file)
	:ArchiveProtocol(localFile,file)
{
	Type = Protocol::Rpm;
	Code = 5;
	Prefix += "#rpm:";
	ReadOnly = TRUE;
}

RpmProtocol::~RpmProtocol()
{}

void RpmProtocol::initCommand(QStrList& cmd)
{ cmd.append("rpm"); cmd.append("-qp");}

bool RpmProtocol::thread_updateEntries()
{
	rawEntries->clear();
	DirDict->clear();
	TreeItem	*root = new TreeItem("/");
	DirDict->insert("/",root);
	QStrList	cmd;
	QString		str;
	int		status;
	initCommand(cmd);
	cmd.append("-l");
	cmd.append("--dump");
	cmd.append(LocalFile.data());
	if (!executeCommand("rpm",cmd)) return FALSE;
	char	buf[2048], *last;
	while (1) {
		if (!fgets(buf,2048,fout)) break;
		strtok_r(buf,"\r\n",&last);
		FileInfo	*fi = new FileInfo(buf,Code);
		str = Prefix.data();
		str += fi->fileName();
		if (fi->isDir() && str[str.length()-1] != '/') str += '/';
		fi->setPath(str.data());
		processEntry(fi);
		rawEntries->append(fi);
	}
	finishCommand();
	if (WIFEXITED(status)) {
		updateFlag = FALSE;
		return TRUE;
	}
	updateFlag = TRUE;
	return FALSE;
}

void RpmProtocol::createParentStr(QString& Str, FileInfo *fi)
{
	Str.truncate(0);
#define Date	fi->lastModified().date()
#define Time	fi->lastModified().time()
	Str.sprintf("%d %d %o %s %s 0 0 0 X",fi->size(),time(0),040755,fi->owner(),fi->group());
#undef 	Date
#undef	Time
}

bool RpmProtocol::extract(const char *src, const char *dest, ProgressDlg *dlg)
{ ErrorMsg = i18n("Rpm archives only support browsing"); return FALSE;}
