/*
 * SystemControl.cpp
 *
 *  Created on: 25.01.2013
 *      Author: georg
 */

#include "SystemControl.h"

const std::string SystemControl::loadedKernelmodules = "/proc/modules";
const std::string SystemControl::FTDI_kernelmodule = "ftdi_sio";

SystemControl::SystemControl() {

}

SystemControl::~SystemControl() {

}

/**
 * If the kernel version is to old, -1 will be returned.
 */
int SystemControl::searchMissingDriver(){
	struct utsname systemInformation;
	uname(&systemInformation);

	std::string kernelVersion = systemInformation.release;

	// Write the first two numbers of the kernel version in "firstNumber" and "secondNumber"
	// return -1 if kernel is to old
	int firstNumber = 0;
	int secondNumber = 0;
	int counter = kernelVersion.find('.');
	int secondCounter = kernelVersion.find('.', counter+1);
	std::string tmp;
	std::stringstream ss;
	if(counter < 500){
		tmp = kernelVersion.substr(0, counter);
		ss << tmp;
		ss >> firstNumber;
		if(firstNumber == firstKernelVersionNumber && secondCounter < 500){
			ss.clear();
			tmp = kernelVersion.substr(counter+1, secondCounter - (counter+1));
			ss << tmp;
			ss >> secondNumber;
			if(secondKernelVersionNumber > secondNumber){
				std::cout << "Kernel version is to old.\n";
				return -1;
			}
		} else if(firstKernelVersionNumber > firstNumber){
			std::cout << "Kernel version is to old.\n";
			return -1;
		}
	} else {
		std::cout << "Can't find the kernel version.\n";
		return -1;
	}

	return 0;
}

/**
 * Searches for the FTDI kernel module. The module can only be found if a FTDI-chip is connected to the computer.
 * Return value -1 indicates that no module was found.
 */
int SystemControl::searchFor_FTDI_kernelModul(){
	bool kernelModulFound = false;
	std::ifstream file;
	std::string line;
	file.open(loadedKernelmodules.c_str(), std::ios::in);
	while (!file.eof())		          				// while data reading
	{
		getline(file, line);        				// read line
		unsigned int found = 0;
		found = line.find(FTDI_kernelmodule);
		if(found != std::string::npos && found <= line.length()){
			kernelModulFound = true;
		}
	}
	file.close();
	if(kernelModulFound){
		return 0;
	} else {
		std::cout << "Can't find '" << FTDI_kernelmodule << "' kernelmodule.\n";
		return -1;
	}
}
