Switch "command-like" options --list-cinemas and --list-dkdm-cpls to actual commands.
[dcpomatic.git] / src / lib / kdm_cli.cc
index 6365c195962217c341cba75713346559614a1302..f63fd2a550d30275c1a3ed16e468ddf79efb12d2 100644 (file)
@@ -27,7 +27,7 @@
 #include "cinema.h"
 #include "config.h"
 #include "dkdm_wrapper.h"
-#include "emailer.h"
+#include "email.h"
 #include "exceptions.h"
 #include "film.h"
 #include "kdm_with_metadata.h"
 #include <dcp/certificate.h>
 #include <dcp/decrypted_kdm.h>
 #include <dcp/encrypted_kdm.h>
+#include <dcp/filesystem.h>
 #include <getopt.h>
-#include <iostream>
 
 
-using std::cerr;
-using std::cout;
 using std::dynamic_pointer_cast;
 using std::list;
 using std::make_shared;
@@ -57,53 +55,52 @@ using namespace dcpomatic;
 
 
 static void
-help ()
+help (std::function<void (string)> out)
 {
-       cerr << "Syntax: " << program_name << " [OPTION] <FILM|CPL-ID|DKDM>\n"
-               "  -h, --help                               show this help\n"
-               "  -o, --output                             output file or directory\n"
-               "  -K, --filename-format                    filename format for KDMs\n"
-               "  -Z, --container-name-format              filename format for ZIP containers\n"
-               "  -f, --valid-from                         valid from time (in local time zone of the cinema) (e.g. \"2013-09-28 01:41:51\") or \"now\"\n"
-               "  -t, --valid-to                           valid to time (in local time zone of the cinema) (e.g. \"2014-09-28 01:41:51\")\n"
-               "  -d, --valid-duration                     valid duration (e.g. \"1 day\", \"4 hours\", \"2 weeks\")\n"
-               "  -F, --formulation                        modified-transitional-1, multiple-modified-transitional-1, dci-any or dci-specific [default modified-transitional-1]\n"
-               "  -p, --disable-forensic-marking-picture   disable forensic marking of pictures essences\n"
-               "  -a, --disable-forensic-marking-audio     disable forensic marking of audio essences (optionally above a given channel, e.g 12)\n"
-               "  -e, --email                              email KDMs to cinemas\n"
-               "  -z, --zip                                ZIP each cinema's KDMs into its own file\n"
-               "  -v, --verbose                            be verbose\n"
-               "  -c, --cinema                             specify a cinema, either by name or email address\n"
-               "  -S, --screen                             screen description\n"
-               "  -C, --certificate                        file containing projector certificate\n"
-               "  -T, --trusted-device                     file containing a trusted device's certificate\n"
-               "      --list-cinemas                       list known cinemas from the DCP-o-matic settings\n"
-               "      --list-dkdm-cpls                     list CPLs for which DCP-o-matic has DKDMs\n\n"
-               "CPL-ID must be the ID of a CPL that is mentioned in DCP-o-matic's DKDM list.\n\n"
-               "For example:\n\n"
-               "Create KDMs for my_great_movie to play in all of Fred's Cinema's screens for the next two weeks and zip them up.\n"
-               "(Fred's Cinema must have been set up in DCP-o-matic's KDM window)\n\n"
-               "\t" << program_name << " -c \"Fred's Cinema\" -f now -d \"2 weeks\" -z my_great_movie\n\n";
+       out (String::compose("Syntax: %1 [OPTION] [COMMAND] <FILM|CPL-ID|DKDM>", program_name));
+       out ("Commands:");
+       out ("create          create KDMs; default if no other command is specified");
+       out ("list-cinemas    list known cinemas from DCP-o-matic settings");
+       out ("list-dkdm-cpls  list CPLs for which DCP-o-matic has DKDMs");
+       out ("  -h, --help                               show this help");
+       out ("  -o, --output <path>                      output file or directory");
+       out ("  -K, --filename-format <format>           filename format for KDMs");
+       out ("  -Z, --container-name-format <format>     filename format for ZIP containers");
+       out ("  -f, --valid-from <time>                  valid from time (e.g. \"2013-09-28T01:41:51+04:00\", \"2018-01-01T12:00:30\") or \"now\"");
+       out ("  -t, --valid-to <time>                    valid to time (e.g. \"2014-09-28T01:41:51\")");
+       out ("  -d, --valid-duration <duration>          valid duration (e.g. \"1 day\", \"4 hours\", \"2 weeks\")");
+       out ("  -F, --formulation <formulation>          modified-transitional-1, multiple-modified-transitional-1, dci-any or dci-specific [default modified-transitional-1]");
+       out ("  -p, --disable-forensic-marking-picture   disable forensic marking of pictures essences");
+       out ("  -a, --disable-forensic-marking-audio     disable forensic marking of audio essences (optionally above a given channel, e.g 12)");
+       out ("  -e, --email                              email KDMs to cinemas");
+       out ("  -z, --zip                                ZIP each cinema's KDMs into its own file");
+       out ("  -v, --verbose                            be verbose");
+       out ("  -c, --cinema <name|email>                cinema name (when using -C) or name/email (to filter cinemas)");
+       out ("  -S, --screen <name>                      screen name (when using -C) or screen name (to filter screens when using -c)");
+       out ("  -C, --projector-certificate <file>       file containing projector certificate");
+       out ("  -T, --trusted-device-certificate <file>  file containing a trusted device's certificate");
+       out ("      --decryption-key <file>              file containing the private key which can decrypt the given DKDM");
+       out ("                                           (DCP-o-matic's configured private key will be used otherwise)");
+       out ("      --cinemas-file <file>                use the given file as a list of cinemas instead of the current configuration");
+       out ("");
+       out ("CPL-ID must be the ID of a CPL that is mentioned in DCP-o-matic's DKDM list.");
+       out ("");
+       out ("For example:");
+       out ("");
+       out ("Create KDMs for my_great_movie to play in all of Fred's Cinema's screens for the next two weeks and zip them up.");
+       out ("(Fred's Cinema must have been set up in DCP-o-matic's KDM window)");
+       out ("");
+       out (String::compose("\t%1 -c \"Fred's Cinema\" -f now -d \"2 weeks\" -z my_great_movie", program_name));
 }
 
 
-static void
-error (string m)
+class KDMCLIError : public std::runtime_error
 {
-       cerr << program_name << ": " << m << "\n";
-       exit (EXIT_FAILURE);
-}
-
-
-static boost::posix_time::ptime
-time_from_string (string t)
-{
-       if (t == "now") {
-               return boost::posix_time::second_clock::local_time ();
-       }
-
-       return boost::posix_time::time_from_string (t);
-}
+public:
+       KDMCLIError (std::string message)
+               : std::runtime_error (String::compose("%1: %2", program_name, message).c_str())
+       {}
+};
 
 
 static boost::posix_time::time_duration
@@ -115,8 +112,7 @@ duration_from_string (string d)
        string const unit (unit_buf);
 
        if (N == 0) {
-               cerr << "Could not understand duration \"" << d << "\"\n";
-               exit (EXIT_FAILURE);
+               throw KDMCLIError (String::compose("could not understand duration \"%1\"", d));
        }
 
        if (unit == "year" || unit == "years") {
@@ -129,8 +125,7 @@ duration_from_string (string d)
                return boost::posix_time::time_duration (N, 0, 0, 0);
        }
 
-       cerr << "Could not understand duration \"" << d << "\"\n";
-       exit (EXIT_FAILURE);
+       throw KDMCLIError (String::compose("could not understand duration \"%1\"", d));
 }
 
 
@@ -149,7 +144,8 @@ write_files (
        boost::filesystem::path output,
        dcp::NameFormat container_name_format,
        dcp::NameFormat filename_format,
-       bool verbose
+       bool verbose,
+       std::function<void (string)> out
        )
 {
        if (zip) {
@@ -162,7 +158,7 @@ write_files (
                        );
 
                if (verbose) {
-                       cout << "Wrote " << N << " ZIP files to " << output << "\n";
+                       out (String::compose("Wrote %1 ZIP files to %2", N, output));
                }
        } else {
                int const N = write_files (
@@ -171,7 +167,7 @@ write_files (
                        );
 
                if (verbose) {
-                       cout << "Wrote " << N << " KDM files to " << output << "\n";
+                       out (String::compose("Wrote %1 KDM files to %2", N, output));
                }
        }
 }
@@ -192,8 +188,7 @@ find_cinema (string cinema_name)
        }
 
        if (i == cinemas.end ()) {
-               cerr << program_name << ": could not find cinema \"" << cinema_name << "\"\n";
-               exit (EXIT_FAILURE);
+               throw KDMCLIError (String::compose("could not find cinema \"%1\"", cinema_name));
        }
 
        return *i;
@@ -203,19 +198,20 @@ find_cinema (string cinema_name)
 static
 void
 from_film (
-       list<shared_ptr<Screen>> screens,
+       vector<shared_ptr<Screen>> screens,
        boost::filesystem::path film_dir,
        bool verbose,
        boost::filesystem::path output,
        dcp::NameFormat container_name_format,
        dcp::NameFormat filename_format,
-       boost::posix_time::ptime valid_from,
-       boost::posix_time::ptime valid_to,
+       dcp::LocalTime valid_from,
+       dcp::LocalTime valid_to,
        dcp::Formulation formulation,
        bool disable_forensic_marking_picture,
        optional<int> disable_forensic_marking_audio,
        bool email,
-       bool zip
+       bool zip,
+       std::function<void (string)> out
        )
 {
        shared_ptr<Film> film;
@@ -223,44 +219,60 @@ from_film (
                film = make_shared<Film>(film_dir);
                film->read_metadata ();
                if (verbose) {
-                       cout << "Read film " << film->name () << "\n";
+                       out (String::compose("Read film %1", film->name()));
                }
        } catch (std::exception& e) {
-               cerr << program_name << ": error reading film `" << film_dir.string() << "' (" << e.what() << ")\n";
-               exit (EXIT_FAILURE);
+               throw KDMCLIError (String::compose("error reading film \"%1\" (%2)", film_dir.string(), e.what()));
        }
 
        /* XXX: allow specification of this */
        vector<CPLSummary> cpls = film->cpls ();
        if (cpls.empty ()) {
-               error ("no CPLs found in film");
+               throw KDMCLIError ("no CPLs found in film");
        } else if (cpls.size() > 1) {
-               error ("more than one CPL found in film");
+               throw KDMCLIError ("more than one CPL found in film");
        }
 
        auto cpl = cpls.front().cpl_file;
 
+       std::vector<KDMCertificatePeriod> period_checks;
+
        try {
                list<KDMWithMetadataPtr> kdms;
                for (auto i: screens) {
-                       auto p = kdm_for_screen (film, cpl, i, valid_from, valid_to, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
+                       std::function<dcp::DecryptedKDM (dcp::LocalTime, dcp::LocalTime)> make_kdm = [film, cpl](dcp::LocalTime begin, dcp::LocalTime end) {
+                               return film->make_kdm(cpl, begin, end);
+                       };
+                       auto p = kdm_for_screen(make_kdm, i, valid_from, valid_to, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio, period_checks);
                        if (p) {
                                kdms.push_back (p);
                        }
                }
-               write_files (kdms, zip, output, container_name_format, filename_format, verbose);
+
+               if (find_if(
+                       period_checks.begin(),
+                       period_checks.end(),
+                       [](KDMCertificatePeriod const& p) { return p.overlap == KDMCertificateOverlap::KDM_OUTSIDE_CERTIFICATE; }
+                  ) != period_checks.end()) {
+                       throw KDMCLIError(
+                               "Some KDMs would have validity periods which are completely outside the recipient certificate periods.  Such KDMs are very unlikely to work, so will not be created."
+                               );
+               }
+
+               if (find_if(
+                       period_checks.begin(),
+                       period_checks.end(),
+                       [](KDMCertificatePeriod const& p) { return p.overlap == KDMCertificateOverlap::KDM_OVERLAPS_CERTIFICATE; }
+                  ) != period_checks.end()) {
+                       out("For some of these KDMs the recipient certificate's validity period will not cover the whole of the KDM validity period.  This might cause problems with the KDMs.");
+               }
+
+               write_files (kdms, zip, output, container_name_format, filename_format, verbose, out);
                if (email) {
-                       send_emails ({kdms}, container_name_format, filename_format, film->dcp_name());
+                       send_emails ({kdms}, container_name_format, filename_format, film->dcp_name(), {});
                }
        } catch (FileError& e) {
-               cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
-               exit (EXIT_FAILURE);
-       } catch (KDMError& e) {
-               cerr << program_name << ": " << e.what() << "\n";
-               exit (EXIT_FAILURE);
-       } catch (runtime_error& e) {
-               cerr << program_name << ": " << e.what() << "\n";
-               exit (EXIT_FAILURE);
+               throw KDMCLIError (String::compose("%1 (%2)", e.what(), e.file().string()));
        }
 }
 
@@ -285,7 +297,7 @@ sub_find_dkdm (shared_ptr<DKDMGroup> group, string cpl_id)
                }
        }
 
-       return optional<dcp::EncryptedKDM>();
+       return {};
 }
 
 
@@ -313,7 +325,7 @@ kdm_from_dkdm (
        /* Signer for new KDM */
        auto signer = Config::instance()->signer_chain ();
        if (!signer->valid ()) {
-               error ("signing certificate chain is invalid.");
+               throw KDMCLIError ("signing certificate chain is invalid.");
        }
 
        /* Make a new empty KDM and add the keys from the DKDM to it */
@@ -336,19 +348,20 @@ kdm_from_dkdm (
 static
 void
 from_dkdm (
-       list<shared_ptr<Screen>> screens,
+       vector<shared_ptr<Screen>> screens,
        dcp::DecryptedKDM dkdm,
        bool verbose,
        boost::filesystem::path output,
        dcp::NameFormat container_name_format,
        dcp::NameFormat filename_format,
-       boost::posix_time::ptime valid_from,
-       boost::posix_time::ptime valid_to,
+       dcp::LocalTime valid_from,
+       dcp::LocalTime valid_to,
        dcp::Formulation formulation,
        bool disable_forensic_marking_picture,
        optional<int> disable_forensic_marking_audio,
        bool email,
-       bool zip
+       bool zip,
+       std::function<void (string)> out
        )
 {
        dcp::NameFormat::Map values;
@@ -360,98 +373,106 @@ from_dkdm (
                                continue;
                        }
 
-                       dcp::LocalTime begin(valid_from, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
-                       dcp::LocalTime end(valid_to, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
-
                        auto const kdm = kdm_from_dkdm(
                                                        dkdm,
                                                        i->recipient.get(),
                                                        i->trusted_device_thumbprints(),
-                                                       begin,
-                                                       end,
+                                                       valid_from,
+                                                       valid_to,
                                                        formulation,
                                                        disable_forensic_marking_picture,
                                                        disable_forensic_marking_audio
                                                        );
 
                        dcp::NameFormat::Map name_values;
-                       name_values['c'] = i->cinema->name;
+                       name_values['c'] = i->cinema ? i->cinema->name : "";
                        name_values['s'] = i->name;
-                       name_values['f'] = dkdm.annotation_text().get_value_or("");
-                       name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
-                       name_values['e'] = end.date() + " " + end.time_of_day(true, false);
+                       name_values['f'] = kdm.content_title_text();
+                       name_values['b'] = valid_from.date() + " " + valid_from.time_of_day(true, false);
+                       name_values['e'] = valid_to.date() + " " + valid_to.time_of_day(true, false);
                        name_values['i'] = kdm.cpl_id();
 
-                       kdms.push_back (make_shared<KDMWithMetadata>(name_values, i->cinema.get(), i->cinema->emails, kdm));
+                       kdms.push_back(make_shared<KDMWithMetadata>(name_values, i->cinema.get(), i->cinema ? i->cinema->emails : vector<string>(), kdm));
                }
-               write_files (kdms, zip, output, container_name_format, filename_format, verbose);
+               write_files (kdms, zip, output, container_name_format, filename_format, verbose, out);
                if (email) {
-                       send_emails ({kdms}, container_name_format, filename_format, dkdm.annotation_text().get_value_or(""));
+                       send_emails ({kdms}, container_name_format, filename_format, dkdm.annotation_text().get_value_or(""), {});
                }
        } catch (FileError& e) {
-               cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
-               exit (EXIT_FAILURE);
-       } catch (KDMError& e) {
-               cerr << program_name << ": " << e.what() << "\n";
-               exit (EXIT_FAILURE);
-       } catch (NetworkError& e) {
-               cerr << program_name << ": " << e.what() << "\n";
-               exit (EXIT_FAILURE);
+               throw KDMCLIError (String::compose("%1 (%2)", e.what(), e.file().string()));
        }
 }
 
 
 static
 void
-dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent)
+dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent, std::function<void (string)> out)
 {
+       auto const indent_string = string(indent, ' ');
+
        if (indent > 0) {
-               for (int i = 0; i < indent; ++i) {
-                       cout << " ";
-               }
-               cout << group->name() << "\n";
+               out (indent_string + group->name());
        }
        for (auto i: group->children()) {
                auto g = dynamic_pointer_cast<DKDMGroup>(i);
                if (g) {
-                       dump_dkdm_group (g, indent + 2);
+                       dump_dkdm_group (g, indent + 2, out);
                } else {
-                       for (int j = 0; j < indent; ++j) {
-                               cout << " ";
-                       }
                        auto d = dynamic_pointer_cast<DKDM>(i);
                        assert(d);
-                       cout << d->dkdm().cpl_id() << "\n";
+                       out (indent_string + d->dkdm().cpl_id());
                }
        }
 }
 
 
-int
-kdm_cli (int argc, char* argv[])
+static
+dcp::LocalTime
+time_from_string(string time)
 {
-       boost::filesystem::path output = ".";
+       if (time == "now") {
+               return {};
+       }
+
+       if (time.length() > 10 && time[10] == ' ') {
+               time[10] = 'T';
+       }
+
+       return dcp::LocalTime(time);
+}
+
+
+optional<string>
+kdm_cli (int argc, char* argv[], std::function<void (string)> out)
+try
+{
+       boost::filesystem::path output = dcp::filesystem::current_path();
        auto container_name_format = Config::instance()->kdm_container_name_format();
        auto filename_format = Config::instance()->kdm_filename_format();
        optional<string> cinema_name;
        shared_ptr<Cinema> cinema;
-       string screen_description;
-       list<shared_ptr<Screen>> screens;
+       optional<boost::filesystem::path> projector_certificate;
+       optional<boost::filesystem::path> decryption_key;
+       optional<string> screen;
+       vector<shared_ptr<Screen>> screens;
        optional<dcp::EncryptedKDM> dkdm;
-       optional<boost::posix_time::ptime> valid_from;
-       optional<boost::posix_time::ptime> valid_to;
+       optional<dcp::LocalTime> valid_from;
+       optional<dcp::LocalTime> valid_to;
        bool zip = false;
-       bool list_cinemas = false;
-       bool list_dkdm_cpls = false;
+       string command = "create";
        optional<string> duration_string;
        bool verbose = false;
        dcp::Formulation formulation = dcp::Formulation::MODIFIED_TRANSITIONAL_1;
        bool disable_forensic_marking_picture = false;
        optional<int> disable_forensic_marking_audio;
        bool email = false;
+       optional<boost::filesystem::path> cinemas_file;
 
        program_name = argv[0];
 
+       /* Reset getopt() so we can call this method several times in one test process */
+       optind = 1;
+
        int option_index = 0;
        while (true) {
                static struct option long_options[] = {
@@ -470,14 +491,14 @@ kdm_cli (int argc, char* argv[])
                        { "verbose", no_argument, 0, 'v' },
                        { "cinema", required_argument, 0, 'c' },
                        { "screen", required_argument, 0, 'S' },
-                       { "certificate", required_argument, 0, 'C' },
-                       { "trusted-device", required_argument, 0, 'T' },
-                       { "list-cinemas", no_argument, 0, 'B' },
-                       { "list-dkdm-cpls", no_argument, 0, 'D' },
+                       { "projector-certificate", required_argument, 0, 'C' },
+                       { "trusted-device-certificate", required_argument, 0, 'T' },
+                       { "decryption-key", required_argument, 0, 'G' },
+                       { "cinemas-file", required_argument, 0, 'E' },
                        { 0, 0, 0, 0 }
                };
 
-               int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pae::zvc:S:C:T:BD", long_options, &option_index);
+               int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pae::zvc:S:C:T:E:G:", long_options, &option_index);
 
                if (c == -1) {
                        break;
@@ -485,8 +506,8 @@ kdm_cli (int argc, char* argv[])
 
                switch (c) {
                case 'h':
-                       help ();
-                       exit (EXIT_SUCCESS);
+                       help (out);
+                       return {};
                case 'o':
                        output = optarg;
                        break;
@@ -497,10 +518,10 @@ kdm_cli (int argc, char* argv[])
                        container_name_format = dcp::NameFormat (optarg);
                        break;
                case 'f':
-                       valid_from = time_from_string (optarg);
+                       valid_from = time_from_string(optarg);
                        break;
                case 't':
-                       valid_to = time_from_string (optarg);
+                       valid_to = dcp::LocalTime(optarg);
                        break;
                case 'd':
                        duration_string = optarg;
@@ -515,7 +536,7 @@ kdm_cli (int argc, char* argv[])
                        } else if (string(optarg) == "dci-specific") {
                                formulation = dcp::Formulation::DCI_SPECIFIC;
                        } else {
-                               error ("unrecognised KDM formulation " + string (optarg));
+                               throw KDMCLIError ("unrecognised KDM formulation " + string (optarg));
                        }
                        break;
                case 'p':
@@ -544,84 +565,113 @@ kdm_cli (int argc, char* argv[])
                           (for lookup) and by creating a Cinema which the next Screen will be added to.
                        */
                        cinema_name = optarg;
-                       cinema = make_shared<Cinema>(optarg, list<string>(), "", 0, 0);
+                       cinema = make_shared<Cinema>(optarg, vector<string>(), "");
                        break;
                case 'S':
-                       screen_description = optarg;
+                       /* Similarly, this could be the name of a new (temporary) screen or the name of a screen
+                        * to search for.
+                        */
+                       screen = optarg;
                        break;
                case 'C':
-               {
-                       /* Make a new screen and add it to the current cinema */
-                       dcp::CertificateChain chain (dcp::file_to_string(optarg));
-                       auto screen = make_shared<Screen>(screen_description, "", chain.leaf(), vector<TrustedDevice>());
-                       if (cinema) {
-                               cinema->add_screen (screen);
-                       }
-                       screens.push_back (screen);
+                       projector_certificate = optarg;
                        break;
-               }
                case 'T':
                        /* A trusted device ends up in the last screen we made */
                        if (!screens.empty ()) {
                                screens.back()->trusted_devices.push_back(TrustedDevice(dcp::Certificate(dcp::file_to_string(optarg))));
                        }
                        break;
-               case 'B':
-                       list_cinemas = true;
+               case 'G':
+                       decryption_key = optarg;
                        break;
-               case 'D':
-                       list_dkdm_cpls = true;
+               case 'E':
+                       cinemas_file = optarg;
                        break;
                }
        }
 
-       if (list_cinemas) {
+       vector<string> commands = {
+               "create",
+               "list-cinemas",
+               "list-dkdm-cpls"
+       };
+
+       if (optind < argc - 1) {
+               /* Command with some KDM / CPL / whever specified afterwards */
+               command = argv[optind++];
+       } else if (optind < argc) {
+               /* Look for a valid command, hoping that it's not the name of the KDM / CPL / whatever */
+               if (std::find(commands.begin(), commands.end(), argv[optind]) != commands.end()) {
+                       command = argv[optind];
+               }
+       }
+
+       if (std::find(commands.begin(), commands.end(), command) == commands.end()) {
+               throw KDMCLIError(String::compose("Unrecognised command %1", command));
+       }
+
+       if (cinemas_file) {
+               Config::instance()->set_cinemas_file(*cinemas_file);
+       }
+
+       if (projector_certificate) {
+               /* Make a new screen and add it to the current cinema */
+               dcp::CertificateChain chain(dcp::file_to_string(*projector_certificate));
+               auto screen_to_add = std::make_shared<Screen>(screen.get_value_or(""), "", chain.leaf(), boost::none, vector<TrustedDevice>());
+               if (cinema) {
+                       cinema->add_screen(screen_to_add);
+               }
+               screens.push_back(screen_to_add);
+       }
+
+       if (command == "list-cinemas") {
                auto cinemas = Config::instance()->cinemas ();
                for (auto i: cinemas) {
-                       cout << i->name << " (" << Emailer::address_list (i->emails) << ")\n";
+                       out (String::compose("%1 (%2)", i->name, Email::address_list(i->emails)));
                }
-               exit (EXIT_SUCCESS);
+               return {};
        }
 
-       if (list_dkdm_cpls) {
-               dump_dkdm_group (Config::instance()->dkdms(), 0);
-               exit (EXIT_SUCCESS);
+       if (command == "list-dkdm-cpls") {
+               dump_dkdm_group (Config::instance()->dkdms(), 0, out);
+               return {};
        }
 
        if (!duration_string && !valid_to) {
-               error ("you must specify a --valid-duration or --valid-to");
+               throw KDMCLIError ("you must specify a --valid-duration or --valid-to");
        }
 
        if (!valid_from) {
-               error ("you must specify --valid-from");
+               throw KDMCLIError ("you must specify --valid-from");
        }
 
        if (optind >= argc) {
-               help ();
-               exit (EXIT_FAILURE);
+               throw KDMCLIError ("no film, CPL ID or DKDM specified");
        }
 
        if (screens.empty()) {
                if (!cinema_name) {
-                       error ("you must specify either a cinema or one or more screens using certificate files");
+                       throw KDMCLIError ("you must specify either a cinema or one or more screens using certificate files");
                }
 
                screens = find_cinema (*cinema_name)->screens ();
+               if (screen) {
+                       screens.erase(std::remove_if(screens.begin(), screens.end(), [&screen](shared_ptr<Screen> s) { return s->name != *screen; }), screens.end());
+               }
        }
 
        if (duration_string) {
-               valid_to = valid_from.get() + duration_from_string (*duration_string);
+               valid_to = valid_from.get();
+               valid_to->add(duration_from_string(*duration_string));
        }
 
-       dcpomatic_setup_path_encoding ();
-       dcpomatic_setup ();
-
        if (verbose) {
-               cout << "Making KDMs valid from " << valid_from.get() << " to " << valid_to.get() << "\n";
+               out(String::compose("Making KDMs valid from %1 to %2", valid_from->as_string(), valid_to->as_string()));
        }
 
        string const thing = argv[optind];
-       if (boost::filesystem::is_directory(thing) && boost::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
+       if (dcp::filesystem::is_directory(thing) && dcp::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
                from_film (
                        screens,
                        thing,
@@ -635,22 +685,25 @@ kdm_cli (int argc, char* argv[])
                        disable_forensic_marking_picture,
                        disable_forensic_marking_audio,
                        email,
-                       zip
+                       zip,
+                       out
                        );
        } else {
-               if (boost::filesystem::is_regular_file(thing)) {
+               if (dcp::filesystem::is_regular_file(thing)) {
                        dkdm = dcp::EncryptedKDM (dcp::file_to_string (thing));
                } else {
                        dkdm = find_dkdm (thing);
                }
 
                if (!dkdm) {
-                       error ("could not find film or CPL ID corresponding to " + thing);
+                       throw KDMCLIError ("could not find film or CPL ID corresponding to " + thing);
                }
 
+               string const key = decryption_key ? dcp::file_to_string(*decryption_key) : Config::instance()->decryption_chain()->key().get();
+
                from_dkdm (
                        screens,
-                       dcp::DecryptedKDM (*dkdm, Config::instance()->decryption_chain()->key().get()),
+                       dcp::DecryptedKDM(*dkdm, key),
                        verbose,
                        output,
                        container_name_format,
@@ -661,9 +714,13 @@ kdm_cli (int argc, char* argv[])
                        disable_forensic_marking_picture,
                        disable_forensic_marking_audio,
                        email,
-                       zip
+                       zip,
+                       out
                        );
        }
 
-       return 0;
+       return {};
+} catch (std::exception& e) {
+       return string(e.what());
 }
+