//
// Created by uos on 2022/3/1.
//
#include "RsyncTaskTest.h"
#include <QDateTime>
#include <QDir>

RsyncTaskTestHandle::RsyncTaskTestHandle(QEventLoop *eventLoop)
{
    m_rsyncTask = new RsyncTask();
    m_eventLoop = eventLoop;
}

bool RsyncTaskTestHandle::dataBackup()
{
    m_rsyncTask->setOptions({"-aAXHi", "--verbose", "--delete", "--force", "--sparse", "--stats", "--delete-excluded", "--info=progress2"});
    //m_rsyncTask->enableDryRun(true);
    //m_rsyncTask->setLinkDest(TEST_DATA_DIR"last");
    m_rsyncTask->setSourcePath("/");
#if defined(TEST_DATA_DIR)
    QString dest = QString(TEST_DATA_DIR"/backup/system/snapshots/%1/localhost").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hh_mm_ss"));
#else
    QString dest = QString("/tmp/backup/system/snapshots/%1/localhost").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hh_mm_ss"));
#endif
    QStringList excludes = {
            "/var/lib/docker/*",
            "/var/lib/schroot/*",
            "/lost+found",
            "/cdrom/*",
            "/sdcared/*",
            "/system/*",
            "/var/swapfile",
            "/.snapshots/*",
            "/home/*/**",
            "/data/*/**",
            "/recovery/*",
            "/root/**",
            "/dev/*",
            "/proc/*",
            "/sys/*",
            "/run/*",
            "/mnt/*",
            "/media/*",
            "/lost+found",
            "/opt/*",
            "/var/*"
    };

    //过滤掉备份目录，否则引起递归
#if defined(TEST_DATA_DIR)
    excludes << TEST_DATA_DIR"/backup/*";
#else
    excludes << "/tmp/backup/*";
#endif
    //节省测试时间
    {
        excludes << "/lib/*";
        excludes << "/usr/*";
    }

    m_rsyncTask->setExcludes(excludes);
    QDir dir(dest);
    if (!dir.exists()) {
        dir.mkpath(dest);
    }
    m_rsyncTask->setDestinationPath(dest);
    m_rsyncTask->enableDryRun(true);
    m_rsyncTask->buildArgumentsForBackup();
    m_rsyncTask->start();
    connect(m_rsyncTask, &QThread::finished, [=] {
        m_rsyncTask->deleteLater();
        m_eventLoop->quit();
    });
    connect(m_rsyncTask, &AsyncTask::error, [=] {
        m_rsyncTask->quit();
        Q_EMIT error();
    });

    return false;
}

TEST_F(RsyncTaskTest, all)
{
    RsyncTaskTestHandle rsyncTaskTestHandle(m_loop);
    rsyncTaskTestHandle.dataBackup();
    m_loop->exec();
}