001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package sop.cli.picocli.commands;
006
007import java.io.File;
008import java.io.FileOutputStream;
009import java.io.IOException;
010
011import picocli.CommandLine;
012import sop.Signatures;
013import sop.cli.picocli.SopCLI;
014import sop.exception.SOPGPException;
015import sop.operation.DetachInbandSignatureAndMessage;
016
017@CommandLine.Command(name = "detach-inband-signature-and-message",
018        description = "Split a clearsigned message",
019        exitCodeOnInvalidInput = SOPGPException.UnsupportedOption.EXIT_CODE)
020public class DetachInbandSignatureAndMessageCmd implements Runnable {
021
022    @CommandLine.Option(
023            names = {"--signatures-out"},
024            description = "Destination to which a detached signatures block will be written",
025            paramLabel = "SIGNATURES")
026    File signaturesOut;
027
028    @CommandLine.Option(names = "--no-armor",
029            description = "ASCII armor the output",
030            negatable = true)
031    boolean armor = true;
032
033    @Override
034    public void run() {
035        if (signaturesOut == null) {
036            throw new SOPGPException.MissingArg("--signatures-out is required.");
037        }
038
039        DetachInbandSignatureAndMessage detach = SopCLI.getSop().detachInbandSignatureAndMessage();
040        if (!armor) {
041            detach.noArmor();
042        }
043
044        try {
045            Signatures signatures = detach
046                    .message(System.in).writeTo(System.out);
047            if (!signaturesOut.createNewFile()) {
048                throw new SOPGPException.OutputExists("Destination of --signatures-out already exists.");
049            }
050            signatures.writeTo(new FileOutputStream(signaturesOut));
051        } catch (IOException e) {
052            throw new RuntimeException(e);
053        }
054    }
055}