summaryrefslogtreecommitdiffstats
path: root/src/tools/controller/controller.cpp
blob: 969dd1ef0f0335e97f660a2a7f1a4afbbde31ac6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Application Manager.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QStringList>
#include <QDir>
#include <QTemporaryFile>
#include <QFileInfo>
#include <QDBusConnection>
#include <QDBusPendingReply>
#include <QDBusError>
#include <QMetaObject>

#include <functional>

#include <QtAppManCommon/global.h>
#include <QtAppManCommon/error.h>
#include <QtAppManCommon/exception.h>
#include <QtAppManCommon/unixsignalhandler.h>
#include <QtAppManCommon/qtyaml.h>
#include <QtAppManCommon/dbus-utilities.h>

#include "applicationmanager_interface.h"
#include "packagemanager_interface.h"

#include "interrupthandler.h"

QT_USE_NAMESPACE_AM

class DBus : public QObject // clazy:exclude=missing-qobject-macro
{
public:
    DBus()
    {
        registerDBusTypes();
    }

    void connectToManager() Q_DECL_NOEXCEPT_EXPR(false)
    {
        if (m_manager)
            return;

        auto conn = connectTo(qSL("io.qt.ApplicationManager"));
        m_manager = new IoQtApplicationManagerInterface(qSL("io.qt.ApplicationManager"), qSL("/ApplicationManager"), conn, this);
    }

    void connectToPackager() Q_DECL_NOEXCEPT_EXPR(false)
    {
        if (m_packager)
            return;

        auto conn = connectTo(qSL("io.qt.PackageManager"));
        m_packager = new IoQtPackageManagerInterface(qSL("io.qt.ApplicationManager"), qSL("/PackageManager"), conn, this);
    }

private:
    QDBusConnection connectTo(const QString &iface) Q_DECL_NOEXCEPT_EXPR(false)
    {
        QDBusConnection conn(iface);

        QFile f(QDir::temp().absoluteFilePath(QString(qSL("%1.dbus")).arg(iface)));
        QString dbus;
        if (f.open(QFile::ReadOnly)) {
            dbus = QString::fromUtf8(f.readAll());
            if (dbus == qL1S("system")) {
                conn = QDBusConnection::systemBus();
                dbus = qSL("[system-bus]");
            } else if (dbus.isEmpty()) {
                conn = QDBusConnection::sessionBus();
                dbus = qSL("[session-bus]");
            } else {
                conn = QDBusConnection::connectToBus(dbus, qSL("custom"));
            }
        } else {
            throw Exception(Error::IO, "Could not find the D-Bus interface of a running application manager instance.\n(did you start the appman with '--dbus none'?");
        }

        if (!conn.isConnected()) {
            throw Exception(Error::IO, "Could not connect to the application manager D-Bus interface %1 at %2: %3")
                .arg(iface, dbus, conn.lastError().message());
        }
        return conn;
    }

public:
    IoQtPackageManagerInterface *packager() const
    {
        return m_packager;
    }

    IoQtApplicationManagerInterface *manager() const
    {
        return m_manager;
    }

private:
    IoQtPackageManagerInterface *m_packager = nullptr;
    IoQtApplicationManagerInterface *m_manager = nullptr;
};

static class DBus dbus;


enum Command {
    NoCommand,
    StartApplication,
    DebugApplication,
    StopApplication,
    StopAllApplications,
    ListApplications,
    ShowApplication,
    ListPackages,
    ShowPackage,
    InstallPackage,
    RemovePackage,
    ListInstallationTasks,
    CancelInstallationTask,
    ListInstallationLocations,
    ShowInstallationLocation
};

// REMEMBER to update the completion file util/bash/appman-prompt, if you apply changes below!
static struct {
    Command command;
    const char *name;
    const char *description;
} commandTable[] = {
    { StartApplication, "start-application", "Start an application." },
    { DebugApplication, "debug-application", "Debug an application." },
    { StopApplication,  "stop-application",  "Stop an application." },
    { StopAllApplications,  "stop-all-applications",  "Stop all applications." },
    { ListApplications, "list-applications", "List all installed applications." },
    { ShowApplication,  "show-application",  "Show application meta-data." },
    { ListPackages,     "list-packages",     "List all installed packages." },
    { ShowPackage,      "show-package",      "Show package meta-data." },
    { InstallPackage,   "install-package",   "Install a package." },
    { RemovePackage,    "remove-package",    "Remove a package." },
    { ListInstallationTasks,     "list-installation-tasks",     "List all active installation tasks." },
    { CancelInstallationTask,    "cancel-installation-task",    "Cancel an active installation task." },
    { ListInstallationLocations, "list-installation-locations", "List all installaton locations." },
    { ShowInstallationLocation,  "show-installation-location",  "Show details for installation location." }
};

static Command command(QCommandLineParser &clp)
{
    if (!clp.positionalArguments().isEmpty()) {
        QByteArray cmd = clp.positionalArguments().at(0).toLatin1();

        for (uint i = 0; i < sizeof(commandTable) / sizeof(commandTable[0]); ++i) {
            if (cmd == commandTable[i].name) {
                clp.clearPositionalArguments();
                clp.addPositionalArgument(qL1S(cmd), qL1S(commandTable[i].description), qL1S(cmd));
                return commandTable[i].command;
            }
        }
    }
    return NoCommand;
}

static void startOrDebugApplication(const QString &debugWrapper, const QString &appId,
                                    const QMap<QString, int> &stdRedirections, bool restart,
                                    const QString &documentUrl) Q_DECL_NOEXCEPT_EXPR(false);
static void stopApplication(const QString &appId, bool forceKill = false) Q_DECL_NOEXCEPT_EXPR(false);
static void stopAllApplications() Q_DECL_NOEXCEPT_EXPR(false);
static void listApplications() Q_DECL_NOEXCEPT_EXPR(false);
static void showApplication(const QString &appId, bool asJson = false) Q_DECL_NOEXCEPT_EXPR(false);
static void listPackages() Q_DECL_NOEXCEPT_EXPR(false);
static void showPackage(const QString &packageId, bool asJson = false) Q_DECL_NOEXCEPT_EXPR(false);
static void installPackage(const QString &packageUrl, bool acknowledge) Q_DECL_NOEXCEPT_EXPR(false);
static void removePackage(const QString &packageId, bool keepDocuments, bool force) Q_DECL_NOEXCEPT_EXPR(false);
static void listInstallationTasks() Q_DECL_NOEXCEPT_EXPR(false);
static void cancelInstallationTask(bool all, const QString &taskId) Q_DECL_NOEXCEPT_EXPR(false);
static void listInstallationLocations() Q_DECL_NOEXCEPT_EXPR(false);
static void showInstallationLocation(bool asJson = false) Q_DECL_NOEXCEPT_EXPR(false);

class ThrowingApplication : public QCoreApplication // clazy:exclude=missing-qobject-macro
{
public:
    ThrowingApplication(int &argc, char **argv)
        : QCoreApplication(argc, argv)
    { }

    Exception *exception() const
    {
        return m_exception;
    }

    template <typename T> void runLater(T slot)
    {
        // run the specified function as soon as the event loop is up and running
        QMetaObject::invokeMethod(this, slot, Qt::QueuedConnection);
    }

protected:
    bool notify(QObject *o, QEvent *e) override
    {
        try {
            return QCoreApplication::notify(o, e);
        } catch (const Exception &e) {
            m_exception = new Exception(e);
            exit(3);
            return true;
        }
    }
private:
    Exception *m_exception = nullptr;
};

int main(int argc, char *argv[])
{
    QCoreApplication::setApplicationName(qSL("Qt Application Manager Controller"));
    QCoreApplication::setOrganizationName(qSL("QtProject"));
    QCoreApplication::setOrganizationDomain(qSL("qt-project.org"));
    QCoreApplication::setApplicationVersion(qSL(AM_VERSION));

    ThrowingApplication a(argc, argv);

    QByteArray desc = "\n\nAvailable commands are:\n";
    uint longestName = 0;
    for (uint i = 0; i < sizeof(commandTable) / sizeof(commandTable[0]); ++i)
        longestName = qMax(longestName, qstrlen(commandTable[i].name));
    for (uint i = 0; i < sizeof(commandTable) / sizeof(commandTable[0]); ++i) {
        desc += "  ";
        desc += commandTable[i].name;
        desc += QByteArray(1 + int(longestName - qstrlen(commandTable[i].name)), ' ');
        desc += commandTable[i].description;
        desc += '\n';
    }

    desc += "\nMore information about each command can be obtained by running\n" \
            "  appman-controller <command> --help";

    QCommandLineParser clp;

    clp.addHelpOption();
    clp.addVersionOption();

    clp.addPositionalArgument(qSL("command"), qSL("The command to execute."));

    // ignore unknown options for now -- the sub-commands may need them later
    clp.setOptionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsPositionalArguments);

    // ignore the return value here, as we also accept options we don't know about yet.
    // If an option is really not accepted by a command, the comman specific parsing should report
    // this.
    clp.parse(QCoreApplication::arguments());
    clp.setOptionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsOptions);

    // REMEMBER to update the completion file util/bash/appman-prompt, if you apply changes below!
    try {
        switch (command(clp)) {
        case NoCommand:
            if (clp.isSet(qSL("version")))
                clp.showVersion();

            clp.setApplicationDescription(qSL("\n") + QCoreApplication::applicationName() + qL1S(desc));
            if (clp.isSet(qSL("help")))
                clp.showHelp(0);
            clp.showHelp(1);
            break;

        case StartApplication: {
            clp.addOption({ { qSL("i"), qSL("attach-stdin") }, qSL("Attach the app's stdin to the controller's stdin") });
            clp.addOption({ { qSL("o"), qSL("attach-stdout") }, qSL("Attach the app's stdout to the controller's stdout") });
            clp.addOption({ { qSL("e"), qSL("attach-stderr") }, qSL("Attach the app's stderr to the controller's stderr") });
            clp.addOption({ { qSL("r"), qSL("restart") }, qSL("Before starting, stop the application if it is already running") });
            clp.addPositionalArgument(qSL("application-id"), qSL("The id of an installed application."));
            clp.addPositionalArgument(qSL("document-url"),   qSL("The optional document-url."), qSL("[document-url]"));
            clp.process(a);

            int args = clp.positionalArguments().size();
            if (args < 2 || args > 3)
                clp.showHelp(1);

            QMap<QString, int> stdRedirections;
            if (clp.isSet(qSL("attach-stdin")))
                stdRedirections[qSL("in")] = 0;
            if (clp.isSet(qSL("attach-stdout")))
                stdRedirections[qSL("out")] = 1;
            if (clp.isSet(qSL("attach-stderr")))
                stdRedirections[qSL("err")] = 2;
            bool restart = clp.isSet(qSL("restart"));

            a.runLater(std::bind(startOrDebugApplication,
                                 QString(),
                                 clp.positionalArguments().at(1),
                                 stdRedirections,
                                 restart,
                                 args == 3 ? clp.positionalArguments().at(2) : QString()));
            break;
        }
        case DebugApplication: {
            clp.addOption({ { qSL("i"), qSL("attach-stdin") }, qSL("Attach the app's stdin to the controller's stdin") });
            clp.addOption({ { qSL("o"), qSL("attach-stdout") }, qSL("Attach the app's stdout to the controller's stdout") });
            clp.addOption({ { qSL("e"), qSL("attach-stderr") }, qSL("Attach the app's stderr to the controller's stderr") });
            clp.addOption({ { qSL("r"), qSL("restart") }, qSL("Before starting, stop the application if it is already running") });
            clp.addPositionalArgument(qSL("debug-wrapper"),  qSL("The debug-wrapper specification."));
            clp.addPositionalArgument(qSL("application-id"), qSL("The id of an installed application."));
            clp.addPositionalArgument(qSL("document-url"),   qSL("The optional document-url."), qSL("[document-url]"));
            clp.process(a);

            int args = clp.positionalArguments().size();
            if (args < 3 || args > 4)
                clp.showHelp(1);

            QMap<QString, int> stdRedirections;
            if (clp.isSet(qSL("attach-stdin")))
                stdRedirections[qSL("in")] = 0;
            if (clp.isSet(qSL("attach-stdout")))
                stdRedirections[qSL("out")] = 1;
            if (clp.isSet(qSL("attach-stderr")))
                stdRedirections[qSL("err")] = 2;
            bool restart = clp.isSet(qSL("restart"));

            a.runLater(std::bind(startOrDebugApplication,
                                 clp.positionalArguments().at(1),
                                 clp.positionalArguments().at(2),
                                 stdRedirections,
                                 restart,
                                 args == 3 ? clp.positionalArguments().at(2) : QString()));
            break;
        }
        case StopAllApplications:
            clp.process(a);
            if (clp.positionalArguments().size() != 1)
                clp.showHelp(1);

            a.runLater(stopAllApplications);
            break;

        case StopApplication:
            clp.addOption({ { qSL("f"), qSL("force") }, qSL("Force kill the application.") });
            clp.addPositionalArgument(qSL("application-id"), qSL("The id of an installed application."));
            clp.process(a);

            if (clp.positionalArguments().size() != 2)
                clp.showHelp(1);

            a.runLater(std::bind(stopApplication,
                                 clp.positionalArguments().at(1),
                                 clp.isSet(qSL("f"))));
            break;

        case ListApplications:
            clp.process(a);
            a.runLater(listApplications);
            break;

        case ShowApplication:
            clp.addOption({ qSL("json"), qSL("Output in JSON format instead of YAML.") });
            clp.addPositionalArgument(qSL("application-id"), qSL("The id of an installed application."));
            clp.process(a);

            if (clp.positionalArguments().size() != 2)
                clp.showHelp(1);

            a.runLater(std::bind(showApplication,
                                 clp.positionalArguments().at(1),
                                 clp.isSet(qSL("json"))));
            break;

        case ListPackages:
            clp.process(a);
            a.runLater(listPackages);
            break;

        case ShowPackage:
            clp.addOption({ qSL("json"), qSL("Output in JSON format instead of YAML.") });
            clp.addPositionalArgument(qSL("package-id"), qSL("The id of an installed package."));
            clp.process(a);

            if (clp.positionalArguments().size() != 2)
                clp.showHelp(1);

            a.runLater(std::bind(showPackage,
                                 clp.positionalArguments().at(1),
                                 clp.isSet(qSL("json"))));
            break;

        case InstallPackage:
            clp.addOption({ { qSL("l"), qSL("location") }, qSL("Set a custom installation location (deprecated and ignored)."), qSL("installation-location"), qSL("internal-0") });
            clp.addOption({ { qSL("a"), qSL("acknowledge") }, qSL("Automatically acknowledge the installation (unattended mode).") });
            clp.addPositionalArgument(qSL("package"), qSL("The file name of the package; can be - for stdin."));
            clp.process(a);

            if (clp.positionalArguments().size() != 2)
                clp.showHelp(1);
            if (clp.isSet(qSL("l")))
                fprintf(stderr, "Ignoring the deprecated -l option.\n");

            a.runLater(std::bind(installPackage,
                                 clp.positionalArguments().at(1),
                                 clp.isSet(qSL("a"))));
            break;

        case RemovePackage:
            clp.addOption({ { qSL("f"), qSL("force") }, qSL("Force removal of package.") });
            clp.addOption({ { qSL("k"), qSL("keep-documents") }, qSL("Keep the document folder of the application.") });
            clp.addPositionalArgument(qSL("package-id"), qSL("The id of an installed package."));
            clp.process(a);

            if (clp.positionalArguments().size() != 2)
                clp.showHelp(1);

            a.runLater(std::bind(removePackage,
                                 clp.positionalArguments().at(1),
                                 clp.isSet(qSL("k")),
                                 clp.isSet(qSL("f"))));
            break;

        case ListInstallationTasks:
            clp.process(a);
            a.runLater(listInstallationTasks);
            break;

        case CancelInstallationTask: {
            clp.addPositionalArgument(qSL("task-id"), qSL("The id of an active installation task."));
            clp.addOption({ { qSL("a"), qSL("all") }, qSL("Cancel all active installation tasks.") });
            clp.process(a);

            int args = clp.positionalArguments().size();
            bool all = clp.isSet(qSL("a"));
            if (!(((args == 1) && all) || ((args == 2) && !all)))
                clp.showHelp(1);

            a.runLater(std::bind(cancelInstallationTask,
                                 all,
                                 args == 2 ? clp.positionalArguments().at(1) : QString()));
            break;
        }
        case ListInstallationLocations:
            clp.process(a);
            a.runLater(listInstallationLocations);
            break;

        case ShowInstallationLocation:
            clp.addPositionalArgument(qSL("installation-location"), qSL("The id of an installation location (deprecated and ignored)."));
            clp.addOption({ qSL("json"), qSL("Output in JSON format instead of YAML.") });
            clp.process(a);

            if (clp.positionalArguments().size() > 2)
                clp.showHelp(1);
            if (clp.positionalArguments().size() == 2)
                fprintf(stderr, "Ignoring the deprecated installation-location.\n");

            a.runLater(std::bind(showInstallationLocation,
                                 clp.isSet(qSL("json"))));
            break;
        }

        int result = a.exec();
        if (a.exception())
            throw *a.exception();
        return result;

    } catch (const Exception &e) {
        fprintf(stderr, "ERROR: %s\n", qPrintable(e.errorString()));
        return 1;
    }
}

void startOrDebugApplication(const QString &debugWrapper, const QString &appId,
                             const QMap<QString, int> &stdRedirections, bool restart,
                             const QString &documentUrl = QString()) Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToManager();

    if (restart) {
        bool isStopped = false;

        // pass 0: normal stop / pass 1: force kill
        for (int pass = 0; !isStopped && (pass < 2); ++pass) {
            stopApplication(appId, pass == 0 ? false : true);

            static const int checksPerSecond = 10;

            // check if application has quit for max. 3sec
            for (int i = 0; !isStopped && (i < (3 * checksPerSecond)); ++i) {
                auto stateReply = dbus.manager()->applicationRunState(appId);
                stateReply.waitForFinished();
                if (stateReply.isError())
                    throw Exception(Error::IO, "failed to get the current run-state from application manager: %1").arg(stateReply.error().message());

                if (stateReply.value() == 0 /* NotRunning */)
                    isStopped = true;
                else
                    QThread::currentThread()->msleep(1000 / checksPerSecond);
            }
        }

        if (!isStopped)
            throw Exception("failed to stop application %1 before restarting it").arg(appId);
    }

    // the async lambda below needs to share this variable
    static bool isStarted = false;

    if (!stdRedirections.isEmpty()) {
        // in case application quits -> quit the controller
        QObject::connect(dbus.manager(), &IoQtApplicationManagerInterface::applicationRunStateChanged,
                         qApp, [appId](const QString &id, uint runState) {
            if (isStarted && id == appId && runState == 0 /* NotRunning */) {
                auto getReply = dbus.manager()->get(id);
                getReply.waitForFinished();
                if (getReply.isError())
                    throw Exception(Error::IO, "failed to get exit code from application manager: %1").arg(getReply.error().message());
                fprintf(stdout, "\n --- application has quit ---\n\n");
                auto app = getReply.value();
                qApp->exit(app.value(qSL("lastExitCode"), 1).toInt());
            }
        });
    }

    bool isDebug = !debugWrapper.isEmpty();
    QDBusPendingReply<bool> reply;
    if (stdRedirections.isEmpty()) {
        reply = isDebug ? dbus.manager()->debugApplication(appId, debugWrapper, documentUrl)
                        : dbus.manager()->startApplication(appId, documentUrl);
    } else {
        UnixFdMap fdMap;
        for (auto it = stdRedirections.cbegin(); it != stdRedirections.cend(); ++it)
            fdMap.insert(it.key(), QDBusUnixFileDescriptor(it.value()));

        reply = isDebug ? dbus.manager()->debugApplication(appId, debugWrapper, fdMap, documentUrl)
                        : dbus.manager()->startApplication(appId, fdMap, documentUrl);
    }

    reply.waitForFinished();
    if (reply.isError()) {
        throw Exception(Error::IO, "failed to call %2Application via DBus: %1")
                .arg(reply.error().message()).arg(isDebug ? "debug" : "start");
    }

    isStarted = reply.value();
    if (stdRedirections.isEmpty()) {
        qApp->exit(isStarted ? 0 : 2);
    } else {
        if (!isStarted) {
            qApp->exit(2);
        } else {
            InterruptHandler::install([appId](int) {
                auto reply = dbus.manager()->stopApplication(appId, true);
                reply.waitForFinished();
                qApp->exit(1);
            });
        }
    }
}

void stopApplication(const QString &appId, bool forceKill) Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToManager();

    auto reply = dbus.manager()->stopApplication(appId, forceKill);
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call stopApplication via DBus: %1").arg(reply.error().message());
    qApp->quit();
}

void stopAllApplications() Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToManager();

    auto reply = dbus.manager()->stopAllApplications();
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call stopAllApplications via DBus: %1").arg(reply.error().message());
    qApp->quit();
}

void listApplications() Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToManager();

    auto reply = dbus.manager()->applicationIds();
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call applicationIds via DBus: %1").arg(reply.error().message());

    const auto applicationIds = reply.value();
    for (auto applicationId : applicationIds)
        fprintf(stdout, "%s\n", qPrintable(applicationId));
    qApp->quit();
}

void showApplication(const QString &appId, bool asJson) Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToManager();

    auto reply = dbus.manager()->get(appId);
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to get application via DBus: %1").arg(reply.error().message());

    QVariant app = reply.value();
    fprintf(stdout, "%s\n", asJson ? QJsonDocument::fromVariant(app).toJson().constData()
                                   : QtYaml::yamlFromVariantDocuments({ app }).constData());
    qApp->quit();
}

void listPackages() Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToPackager();

    auto reply = dbus.packager()->packageIds();
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call packageIds via DBus: %1").arg(reply.error().message());

    const auto packageIds = reply.value();
    for (auto packageId : packageIds)
        fprintf(stdout, "%s\n", qPrintable(packageId));
    qApp->quit();
}

void showPackage(const QString &packageId, bool asJson) Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToPackager();

    auto reply = dbus.packager()->get(packageId);
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to get package via DBus: %1").arg(reply.error().message());

    QVariant package = reply.value();
    fprintf(stdout, "%s\n", asJson ? QJsonDocument::fromVariant(package).toJson().constData()
                                   : QtYaml::yamlFromVariantDocuments({ package }).constData());
    qApp->quit();
}

void installPackage(const QString &package, bool acknowledge) Q_DECL_NOEXCEPT_EXPR(false)
{
    QString packageFile = package;

    if (package == qL1S("-")) { // sent via stdin
        bool success = false;

        QTemporaryFile *tf = new QTemporaryFile(qApp);
        QFile in;

        if (tf->open() && in.open(stdin, QIODevice::ReadOnly)) {
            packageFile = tf->fileName();

            while (!in.atEnd() && !tf->error())
                tf->write(in.read(1024 * 1024 * 8));

            success = in.atEnd() && !tf->error();
            tf->flush();
        }

        if (!success)
            throw Exception(Error::IO, "Could not copy from stdin to temporary file %1").arg(package);
    }

    QFileInfo fi(packageFile);
    if (!fi.exists() || !fi.isReadable() || !fi.isFile())
        throw Exception(Error::IO, "Package file is not readable: %1").arg(packageFile);

    fprintf(stdout, "Starting installation of package %s ...\n", qPrintable(packageFile));

    dbus.connectToManager();
    dbus.connectToPackager();

    // all the async lambdas below need to share this variable
    static QString installationId;

    // as soon as we have the manifest available: get the app id and acknowledge the installation

    if (acknowledge) {
        QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskRequestingInstallationAcknowledge,
                         [](const QString &taskId, const QVariantMap &metadata) {
            if (taskId != installationId)
                return;
            QString packageId = metadata.value(qSL("packageId")).toString();
            if (packageId.isEmpty())
                throw Exception(Error::IO, "could not find a valid package id in the package");
            fprintf(stdout, "Acknowledging package installation for '%s'...\n", qPrintable(packageId));
            dbus.packager()->acknowledgePackageInstallation(taskId);
        });
    }

    // on failure: quit

    QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskFailed,
                     [](const QString &taskId, int errorCode, const QString &errorString) {
        if (taskId != installationId)
            return;
        throw Exception(Error::IO, "failed to install package: %1 (code: %2)").arg(errorString).arg(errorCode);
    });

    // on success

    QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskFinished,
                     [](const QString &taskId) {
        if (taskId != installationId)
            return;
        fprintf(stdout, "Package installation finished successfully.\n");
        qApp->quit();
    });

    // start the package installation

    auto reply = dbus.packager()->startPackageInstallation(fi.absoluteFilePath());
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call startPackageInstallation via DBus: %1").arg(reply.error().message());

    installationId = reply.value();
    if (installationId.isEmpty())
        throw Exception(Error::IO, "startPackageInstallation returned an empty taskId");

    // cancel the job on Ctrl+C

    InterruptHandler::install([](int) {
        fprintf(stdout, "Cancelling package installation.\n");
        auto reply = dbus.packager()->cancelTask(installationId);
        reply.waitForFinished();
        qApp->exit(1);
    });
}

void removePackage(const QString &packageId, bool keepDocuments, bool force) Q_DECL_NOEXCEPT_EXPR(false)
{
    fprintf(stdout, "Starting removal of package %s...\n", qPrintable(packageId));

    dbus.connectToManager();
    dbus.connectToPackager();

    // both the async lambdas below need to share this variables
    static QString installationId;

    // on failure: quit

    QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskFailed,
                     [](const QString &taskId, int errorCode, const QString &errorString) {
        if (taskId != installationId)
            return;
        throw Exception(Error::IO, "failed to remove package: %1 (code: %2)").arg(errorString).arg(errorCode);
    });

    // on success

    QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskFinished,
                     [](const QString &taskId) {
        if (taskId != installationId)
            return;
        fprintf(stdout, "Package removal finished successfully.\n");
        qApp->quit();
    });

    // start the package installation

    auto reply = dbus.packager()->removePackage(packageId, keepDocuments, force);
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call removePackage via DBus: %1").arg(reply.error().message());

    installationId = reply.value();
    if (installationId.isEmpty())
        throw Exception(Error::IO, "removePackage returned an empty taskId");
}

void listInstallationTasks() Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToPackager();

    auto reply = dbus.packager()->activeTaskIds();
    reply.waitForFinished();
    if (reply.isError())
        throw Exception(Error::IO, "failed to call activeTaskIds via DBus: %1").arg(reply.error().message());

    const auto taskIds = reply.value();
    for (auto taskId : taskIds)
        fprintf(stdout, "%s\n", qPrintable(taskId));
    qApp->quit();
}


void cancelInstallationTask(bool all, const QString &taskId) Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToPackager();

    // both the async lambdas below need to share this variables
    static QStringList cancelTaskIds;
    static int result = 0;

    if (all) {
        dbus.connectToPackager();

        auto reply = dbus.packager()->activeTaskIds();
        reply.waitForFinished();
        if (reply.isError())
            throw Exception(Error::IO, "failed to call activeTaskIds via DBus: %1").arg(reply.error().message());

        const auto taskIds = reply.value();
        for (auto taskId : taskIds)
            cancelTaskIds << taskId;
    } else {
        cancelTaskIds << taskId;
    }

    if (cancelTaskIds.isEmpty())
        qApp->quit();

    // on task failure

    QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskFailed,
                     [](const QString &taskId, int errorCode, const QString &errorString) {
        if (cancelTaskIds.removeOne(taskId)) {
            if (errorCode != int(Error::Canceled)) {
                fprintf(stdout, "Could not cancel task %s anymore - the installation task already failed (%s).\n",
                        qPrintable(taskId), qPrintable(errorString));
                result |= 2;
            } else {
                fprintf(stdout, "Installation task was canceled successfully.\n");
            }
            if (cancelTaskIds.isEmpty())
                qApp->exit(result);
        }
    });

    // on success

    QObject::connect(dbus.packager(), &IoQtPackageManagerInterface::taskFinished,
                     [](const QString &taskId) {
        if (cancelTaskIds.removeOne(taskId)) {
            fprintf(stdout, "Could not cancel task %s anymore - the installation task already finished successfully.\n",
                    qPrintable(taskId));
            result |= 1;
            if (cancelTaskIds.isEmpty())
                qApp->exit(result);
        }
    });

    for (auto cancelTaskId : qAsConst(cancelTaskIds)) {
        fprintf(stdout, "Canceling installation task %s...\n", qPrintable(cancelTaskId));

        // cancel the task

        auto reply = dbus.packager()->cancelTask(cancelTaskId);
        reply.waitForFinished();
        if (reply.isError())
            throw Exception(Error::IO, "failed to call cancelTask via DBus: %1").arg(reply.error().message());

        if (!reply.value())
            throw Exception(Error::IO, "failed to cancel the installation task.");
    }
}

void listInstallationLocations() Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToPackager();

    auto installationLocation = dbus.packager()->installationLocation().variant().toMap();
    if (!installationLocation.isEmpty())
        fputs("internal-0\n", stdout);
    qApp->quit();
}

void showInstallationLocation(bool asJson) Q_DECL_NOEXCEPT_EXPR(false)
{
    dbus.connectToPackager();

    auto installationLocation = dbus.packager()->installationLocation().variant().toMap();
    fprintf(stdout, "%s\n", asJson ? QJsonDocument::fromVariant(installationLocation).toJson().constData()
                                   : QtYaml::yamlFromVariantDocuments({ installationLocation }).constData());
    qApp->quit();
}