// Copyright (c) 2018-2021, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0

package cmd

import (
	"fmt"
	"sync"
	"time"

	"github.com/choria-io/fisk"
)

type enrollCommand struct {
	command

	cn string
}

func (e *enrollCommand) Setup() (err error) {
	e.cmd = cli.app.Command("enroll", "Enroll with the security provider")
	e.cmd.Flag("config", "Config file to use").PlaceHolder("FILE").StringVar(&configFile)
	e.cmd.Flag("certname", "Custom Certificate Name").StringVar(&e.cn)

	return
}

func (e *enrollCommand) Configure() error {
	err = commonConfigure()
	if err != nil {
		return err
	}

	cfg.DisableSecurityProviderVerify = true

	if e.cn != "" {
		cfg.OverrideCertname = e.cn
	}

	return nil
}

func (e *enrollCommand) Run(wg *sync.WaitGroup) (err error) {
	defer wg.Done()

	fmt.Printf("Enrolling with the Security System using certname %s\n", c.Certname())

	err = c.Enroll(ctx, 250*time.Second, func(digest string, try int) {
		if digest != "" && try <= 1 {
			fmt.Printf("Certificate fingerprint: %s\n\n", digest)
		}
		fmt.Printf("Attempting to download certificate for %s, try %d\n", c.Certname(), try)
	})
	fisk.FatalIfError(err, "Could not enroll")

	return nil
}

func init() {
	cli.commands = append(cli.commands, &enrollCommand{})
}
