#include "lcssregisteroperation.h"
#include <QProcess>
#include <QCoreApplication>
#include <QFile>

#if defined(Q_OS_MAC)
using namespace QInstaller;

namespace
{
QString launchAgentsPath()
{
    return QString("/Library/LaunchAgents");
}
QString launchAgentsPlistPath()
{
    return QString("%1/%2.%3_autolaunch.plist")
        .arg(launchAgentsPath())
        .arg("com.lacie")
        .arg("lcss");
}

bool isAutoLaunchEnabled()
{
    return QFile::exists(launchAgentsPlistPath());
}

bool setAutoLaunchEnabled(bool v, const QString &path)
{
    if (isAutoLaunchEnabled() == v)
        return true;

    const QString cmd("/bin/sh");
    QStringList args{"-c"};
    QStringList launchctlArgs{"-c"};

    if (v) {
        static QString plistXMLContent(R"(<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>KeepAlive</key>
   <true/>
   <key>Label</key>
   <string>com.lacie.lcss</string>
   <key>ProgramArguments</key>
   <array>
       <string>%1</string>
   </array>
</dict>
</plist>
)");
        QString xmlData = plistXMLContent.arg(path);
        args.push_back(QString("echo \"%1\" >> \"%2\"").arg(xmlData).arg(launchAgentsPlistPath()));

        launchctlArgs.push_back(QString("launchctl load \"%1\"").arg(launchAgentsPlistPath()));
    }
    else {
        args.push_back(QString("rm \"%1\"").arg(launchAgentsPlistPath()));

        launchctlArgs.push_back(QString("launchctl unload \"%1\"").arg(launchAgentsPlistPath()));
    }

    QProcess plistProcess;
    QProcess launchctlProcess;

    if (v) {
        plistProcess.start(cmd, args);
        plistProcess.waitForFinished();

        launchctlProcess.start(cmd, launchctlArgs);
        launchctlProcess.waitForFinished();
    }
    else {
        launchctlProcess.start(cmd, launchctlArgs);
        launchctlProcess.waitForFinished();

        plistProcess.start(cmd, args);
        plistProcess.waitForFinished();
    }

    return (plistProcess.exitCode() == 0 && launchctlProcess.exitCode() == 0);
}
}

LCSSRegisterOperation::LCSSRegisterOperation()
{
    setName(QLatin1String("LCSSRegister"));
}

void LCSSRegisterOperation::backup()
{
}

bool LCSSRegisterOperation::performOperation()
{    
    const QStringList args = arguments();

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

    const QString &path = args.first();

    return setAutoLaunchEnabled(true, path);
}

bool LCSSRegisterOperation::undoOperation()
{
    const QStringList args = arguments();

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

    const QString &path = args.at(0);

    return setAutoLaunchEnabled(false, path);
}

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

Operation *LCSSRegisterOperation::clone() const
{
    return new LCSSRegisterOperation();
}
#endif
