/*
 * posix_QrfeHardwareInfo.cpp
 *
 *  Created on: 14.06.2012
 *      Author: stefan.detter
 */

#include <stdio.h>
#include <string.h>

#include <QtGlobal>
#include <QFile>
#include <QStringList>
#include <QrfeGlobal>
#include <QrfeTrace>
#include <QrfeCRC>

#include <sys/ioctl.h>
#include <sys/file.h>
#include <linux/hdreg.h>

bool qrfe_getCpuId( QString & vendor, QString & brand )
{
    QFile cpuinfo("/proc/cpuinfo");

    vendor = brand = "";

    if(!cpuinfo.open(QIODevice::ReadOnly))
    {
        vendor = "Unknown";
        brand = "Unknown";
        return false;
    }

    QString data = QString::fromLatin1(cpuinfo.readAll());
    QStringList list = data.split("\n", QString::SkipEmptyParts);

    foreach(QString s, list)
    {
        if(s.startsWith("vendor_id") || s.startsWith("model name"))
        {
            QStringList set = s.split(":");
            if(set.size() < 2)
                continue;

            QString key = set.at(0);
            QString val = set.at(1);

            if(val.startsWith(" "))
                val.remove(0, 1);

            if(key.startsWith("vendor_id"))
                vendor += val;
            if(key.startsWith("model name"))
                brand += val;
        }
    }

    return (!vendor.isEmpty() && !brand.isEmpty());
}

bool qrfe_getVolumeSerialNumber( quint32 &serial )
{
    QFile fstab("/etc/fstab");

    QString uuid;

    if(!fstab.open(QIODevice::ReadOnly))
    {
        uuid = "Unknown";
        return false;
    }

    QString data = QString::fromLatin1(fstab.readAll());
    QStringList list = data.split(" ", QString::SkipEmptyParts);

    foreach(QString str, list)
    {
        QStringList sublist = str.split("\n", QString::SkipEmptyParts);
        foreach(QString substr, sublist)
        {
            if(substr.startsWith("UUID=") && substr.size() > 5)
                uuid += substr.mid(5);
        }
    }


    QByteArray md5 = QrfeCRC::calcMD5(uuid.toLatin1());

    serial = 0;
    serial += ((uint)(uchar)QrfeCRC::calcXORCS(md5.mid(0, 4))) << 0;
    serial += ((uint)(uchar)QrfeCRC::calcXORCS(md5.mid(4, 4))) << 8;
    serial += ((uint)(uchar)QrfeCRC::calcXORCS(md5.mid(8, 4))) << 16;
    serial += ((uint)(uchar)QrfeCRC::calcXORCS(md5.mid(12, 4))) << 24;

    return true;
}

