/*
Copyright (C) 2006 - 2009 Evan Teran
                   eteran@alum.rit.edu

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.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "DialogAttach.h"
#include "Types.h"

#include <QtDebug>
#include <QMap>
#include <QDir>
#include <QTextStream>

#include <pwd.h>

//------------------------------------------------------------------------------
// Name: DialogAttachUNIX(QWidget *parent)
// Desc: constructor
//------------------------------------------------------------------------------
DialogAttach::DialogAttach(QWidget *parent) : DialogAttachUNIX(parent) {
}

//------------------------------------------------------------------------------
// Name: 
// Desc: 
//------------------------------------------------------------------------------
QMap<edb::pid_t, DialogAttachUNIX::ProcessInfo> DialogAttach::findProcesses() {
	QMap<edb::pid_t, ProcessInfo> procs;
	
	QDir procDir("/proc/");
	QFileInfoList entries = procDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
	
	Q_FOREACH(const QFileInfo &info, entries) {
		if(isNumeric(info.fileName())) {

			const QDir proc(info.absoluteFilePath());		
			const QString status = proc.absolutePath() + "/stat";
			
			ProcessInfo procInfo;
			procInfo.pid = info.fileName().toUInt();
			procInfo.uid = info.ownerId();
			
			struct passwd *pwd = ::getpwuid(procInfo.uid);
			
			if(pwd != 0) {
				procInfo.user = pwd->pw_name;
			}
			
			QFile file(status);
	        if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
				QTextStream in(&file);

				int pid;
				QString name;
				// we already know the pid, so this'll just get read and ignored
				in >> pid;
				// get the name
				in >> name;
				// chop off the silly ( and )
				procInfo.name = name.mid(1);
				procInfo.name.chop(1);

			}
			procs.insert(procInfo.pid, procInfo);
		}
	}
	return procs;
}
