//
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cli

import (
	"github.com/spf13/cobra"

	"github.com/sigstore/cosign/v2/cmd/cosign/cli/generate"
	"github.com/sigstore/cosign/v2/cmd/cosign/cli/options"
)

func Generate() *cobra.Command {
	o := &options.GenerateOptions{}

	cmd := &cobra.Command{
		Use:   "generate",
		Short: "Generates (unsigned) signature payloads from the supplied container image.",
		Long: `Generates an unsigned payload from the supplied container image and flags.
This payload matches the one generated by the "cosign sign" command and can be used if you need
to sign payloads with your own tooling or algorithms.`,
		Example: `  cosign generate [--a key=value] <image uri>

  # Generate a simple payload for an image
  cosign generate <IMAGE>

  # Generate a payload with specific annotations
  cosign generate -a foo=bar <IMAGE>

  # Use this payload in another tool
  gpg --output image.sig --detach-sig <(cosign generate <IMAGE>)`,

		Args:             cobra.ExactArgs(1),
		PersistentPreRun: options.BindViper,
		RunE: func(cmd *cobra.Command, args []string) error {
			annotationMap, err := o.AnnotationsMap()
			if err != nil {
				return err
			}
			return generate.GenerateCmd(cmd.Context(), o.Registry, args[0], annotationMap.Annotations, cmd.OutOrStdout())
		},
	}

	o.AddFlags(cmd)
	return cmd
}
