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.IOException;
008import java.util.ArrayList;
009import java.util.List;
010
011import picocli.CommandLine;
012import sop.Ready;
013import sop.cli.picocli.Print;
014import sop.cli.picocli.SopCLI;
015import sop.exception.SOPGPException;
016import sop.operation.GenerateKey;
017
018@CommandLine.Command(name = "generate-key",
019        description = "Generate a secret key",
020        exitCodeOnInvalidInput = 37)
021public class GenerateKeyCmd implements Runnable {
022
023    @CommandLine.Option(names = "--no-armor",
024            description = "ASCII armor the output",
025            negatable = true)
026    boolean armor = true;
027
028    @CommandLine.Parameters(description = "User-ID, eg. \"Alice <alice@example.com>\"")
029    List<String> userId = new ArrayList<>();
030
031    @Override
032    public void run() {
033        GenerateKey generateKey = SopCLI.getSop().generateKey();
034        for (String userId : userId) {
035            generateKey.userId(userId);
036        }
037
038        if (!armor) {
039            generateKey.noArmor();
040        }
041
042        try {
043            Ready ready = generateKey.generate();
044            ready.writeTo(System.out);
045        } catch (SOPGPException.MissingArg missingArg) {
046            Print.errln("Missing argument.");
047            Print.trace(missingArg);
048            System.exit(missingArg.getExitCode());
049        } catch (SOPGPException.UnsupportedAsymmetricAlgo unsupportedAsymmetricAlgo) {
050            Print.errln("Unsupported asymmetric algorithm.");
051            Print.trace(unsupportedAsymmetricAlgo);
052            System.exit(unsupportedAsymmetricAlgo.getExitCode());
053        } catch (IOException e) {
054            Print.errln("IO Error.");
055            Print.trace(e);
056            System.exit(1);
057        }
058    }
059}