package main

import (
	"errors"
	"os"
	"path"

	"github.com/fleetdm/fleet/v4/pkg/fleethttp"
	"github.com/fleetdm/fleet/v4/server/config"
	"github.com/fleetdm/fleet/v4/server/vulnerabilities"
	"github.com/urfave/cli/v2"
)

func vulnerabilityDataStreamCommand() *cli.Command {
	var dir string
	return &cli.Command{
		Name:  "vulnerability-data-stream",
		Usage: "Download the vulnerability data stream",
		UsageText: `
fleetctl vulnerability-data-stream [options]

Downloads (if needed) the data streams that can be used by the Fleet server to process software for vulnerabilities.
`,
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:        "dir",
				EnvVars:     []string{"DIR"},
				Value:       "",
				Destination: &dir,
				Usage:       "Directory to place the data streams in",
			},
			configFlag(),
			contextFlag(),
			debugFlag(),
		},
		Action: func(c *cli.Context) error {
			if dir == "" {
				return errors.New("No directory provided")
			}

			err := os.MkdirAll(dir, 0o700)
			if err != nil {
				return err
			}

			log(c, "[-] Downloading CPE database...")

			dbPath := path.Join(dir, "cpe.sqlite")
			client := fleethttp.NewClient()
			err = vulnerabilities.SyncCPEDatabase(client, dbPath)
			if err != nil {
				return err
			}

			log(c, " Done\n")

			log(c, "[-] Downloading CVE data streams...")

			err = vulnerabilities.SyncCVEData(dir, config.FleetConfig{})
			if err != nil {
				return err
			}

			log(c, " Done\n")

			log(c, "[+] Data streams successfully downloaded!\n")

			return nil
		},
	}
}
