
#include "Debugger.h"
#include "DebuggerCoreInterface.h"
#include <QFileInfo>
#include <QTextStream>

//------------------------------------------------------------------------------
// Name: symlinkTarget(const QFileInfo &info)
// Desc: 
//------------------------------------------------------------------------------
QString edb::v1::symlinkTarget(const QFileInfo &info) {
#if QT_VERSION < 0x040200
	QString ret;
	#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)
		char buf[PATH_MAX];
		const ssize_t i = readlink(qPrintable(info.absoluteFilePath()), buf, sizeof(buf));
		if(i >= 0) {
			buf[i] = '\0';
			ret = buf;
		}
	#else
		#error "Unsupported Platform"
	#endif
	return ret;
#else
	return info.symLinkTarget();
#endif
}

//------------------------------------------------------------------------------
// Name: getProcessExecutable()
// Desc: 
//------------------------------------------------------------------------------
QString edb::v1::getProcessExecutable() {

	// TODO: make this work after the process has exited!
	//		 or work around the fact that it doesn't work
	//		 if the process has exited.

	QString ret;
	
	
	if(debuggerBase != 0) {
		// TODO: assert attached!
		
		const edb::pid_t pid = debuggerBase->pid();
	#ifdef Q_OS_LINUX
		ret = edb::v1::symlinkTarget(QString().sprintf("/proc/%d/exe", pid));
	#else
		#error "Unsupported Platform"
	#endif
	}
	
	return ret;
}

//------------------------------------------------------------------------------
// Name: getProcessCurrentWorkingDirectory()
// Desc: 
//------------------------------------------------------------------------------
QString edb::v1::getProcessCurrentWorkingDirectory() {
	QString ret;
	if(debuggerBase != 0) {
	
		// TODO: assert attached!
	
		const edb::pid_t pid = debuggerBase->pid();
	#ifdef Q_OS_LINUX
		ret = edb::v1::symlinkTarget(QString().sprintf("/proc/%d/cwd", pid));
	#else
		#error "Unsupported Platform"
	#endif
	}
	return ret;
}

//------------------------------------------------------------------------------
// Name: getProcessArguments()
// Desc: 
//------------------------------------------------------------------------------
QStringList edb::v1::getProcessArguments() {
	QStringList ret;
	if(debuggerBase != 0) {
	
		// TODO: assert attached!
	
		const edb::pid_t pid = debuggerBase->pid();
	#ifdef Q_OS_LINUX
		const QString cmdlineFile(QString().sprintf("/proc/%d/cmdline", pid));
		QFile file(cmdlineFile);

		if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
			QTextStream in(&file);

			QString s;
			QChar ch;

			while(in.status() == QTextStream::Ok) {
				in >> ch;
				if(ch == '\0') {
					if(!s.isEmpty()) {
						ret << s;
					}
					s.clear();
				} else {
					s += ch;
				}
			}

			if(!s.isEmpty()) {
				ret << s;
			}
		}
	#else
		#error "Unsupported Platform"
	#endif
	}
	return ret;
}
