#include "autorunregisteroperation.h"

#include <QDir>
#include <QProcess>

using namespace QInstaller;

#ifdef Q_OS_WIN
namespace {
    bool executeCommand(const QString &cmd)
    {
        QProcess process;
        int ret = process.execute(cmd);
        return (ret != -1 && ret != -2);
    }
}
#endif

AutorunRegisterOperation::AutorunRegisterOperation()
{
    setName(QLatin1String("AutorunRegister"));
}

void AutorunRegisterOperation::backup()
{
}

bool AutorunRegisterOperation::performOperation()
{
    QStringList args = arguments();

    if (args.count() != 2 && args.count() != 3) {
        setError(InvalidArguments);
        setErrorString(QString("Invalid arguments in %0: %1 arguments given, %2 expected%3.")
            .arg(name()).arg(arguments().count()).arg(tr("2 or 3")));
        return false;
    }

    const QString target = args.at(0);
    const QString taskName = args.at(1);
    bool ret = false;

#ifdef Q_OS_WIN
    const QString command0 = QString("schtasks /delete /f /tn \"%1\"")
            .arg(taskName);
    ret = executeCommand(command0);

/* Complicated quote marks enclosing the executable path is workaround for BUG #48264
 * https://support.microsoft.com/en-us/help/823093/a-scheduled-task-does-not-run-when-you-use-schtasks.exe-to-create-it-and-when-the-path-of-the-scheduled-task-contains-a-space */
    const QString command1 = QString("schtasks /create /sc onlogon /tn \"%1\" /rl highest /tr \"'%2'\"")
            .arg(taskName)
            .arg(QDir::toNativeSeparators(target));
    ret = executeCommand(command1);
#endif

    return ret;
}

bool AutorunRegisterOperation::undoOperation()
{
#ifdef Q_OS_WIN
    const QString &taskName = arguments().at(1);
    const QString command = QString("schtasks /delete /f /tn \"%1\"").arg(taskName);
    return executeCommand(command);
#endif

    return true;
}

bool AutorunRegisterOperation::testOperation()
{
    return true;
}

Operation *AutorunRegisterOperation::clone() const
{
    return new AutorunRegisterOperation();
}
