#include <QCoreApplication>
#include <QProcess>
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QDateTime>
#include <QSettings>

void MessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    Q_UNUSED(type); Q_UNUSED(context);
    // 设置输出信息格式
    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString strMessage = QString("%1: %2").arg(strDateTime).arg(msg);
    // 输出信息至文件中（读写、追加形式）
    QFile file(QString("%1/download/porter.log").arg(qApp->applicationDirPath()));
    file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&file);
    stream << strMessage << "\r\n";
    file.flush();
    file.close();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // 日志输出
    qInstallMessageHandler(MessageOutput);

    qDebug() << "\r\n\r\n\r\n";
    QString appDir = QCoreApplication::applicationDirPath();
    QString fmscupdPath = QString("%1/fmscupd.exe").arg(appDir);
    QFile dInfoFile(QString("%1/download/dfilesInfo.txt").arg(appDir));
    QFile resultFile(QString("%1/download/updateresult.txt").arg(appDir));
    QStringList dFilesInfo, bUpdFiles;
    QString error;
    bool updateReault = true;

    // 关闭服务
    QProcess::execute(fmscupdPath, QStringList("-t"));

    // 开始替换文件
    if(dInfoFile.open(QIODevice::ReadOnly))
    {
        dFilesInfo = QString(dInfoFile.readAll()).split(",");
        dInfoFile.close();
    }else
    {
        error  = QString("open dfilesInfo.txt failed [%1]").arg(dInfoFile.errorString());
        qDebug() << error;
        updateReault = false;
        goto end;
    }

    foreach(QString dfile, dFilesInfo)
    {
        if(!dfile.isEmpty())
        {
            QString downloadFile = QString("%1/download/%2").arg(appDir, dfile);
            QString oldFile = QString("%1/%2").arg(appDir, dfile);
            QString newName = QString("%1.bak").arg(oldFile);
            qDebug() << QString("replace file [%1]").arg(oldFile);
            if(!QFile(oldFile).exists())
            {
                qDebug() << "file not exists";
                if(QDir().mkpath(oldFile.left(oldFile.lastIndexOf("/"))))
                {
                    qDebug() << "mkdir successful";
                }else
                {
                    qDebug() << "mkdir failed";
                }
            }else
            {
                qDebug() << "file exists";
                QFile(newName).remove();
                if(QFile().rename(oldFile, newName))
                {
                    qDebug() << "rename successful";
                }else
                {
                    qDebug() << "rename failed";
                }
            }

            if(QFile().copy(downloadFile, oldFile))
            {
                qDebug() << "copy file successful";
            }else
            {
                error = "copy file failed";
                qDebug() << error;
                updateReault = false;
                // 回滚文件
                foreach(QString file, bUpdFiles)
                {
                  qDebug() << QString("rollback file [%1]").arg(file);
                  QFile(file).remove();
                  QFile().rename(QString("%1.bak").arg(file), file);
                }
                break;
            }
            bUpdFiles.append(oldFile);
        }
    }

end:
    if(resultFile.open(QIODevice::WriteOnly))
    {
        QByteArray buf;
        if(updateReault)
        {
            buf = "1";
        }else
        {
            buf = QString("0%1").arg(error).toLatin1();
        }
        resultFile.write(buf);
        resultFile.close();
    }
    // 启动服务
    QProcess::startDetached(fmscupdPath, QStringList(fmscupdPath));
    return 0;
}
