// Package cli provides the interface for the command-line.
package cli

import (
	"fmt"
	"os/exec"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/log"
	"github.com/spf13/cobra"
)

// UpgradeCommand upgrades abra in-place.
var UpgradeCommand = &cobra.Command{
	Use:     "upgrade [flags]",
	Aliases: []string{"u"},
	Short:   "Upgrade abra",
	Long: `Upgrade abra in-place with the latest stable or release candidate.

By default, the latest stable release is downloaded.

Use "--rc/-r" to install the latest release candidate. Please bear in mind that
it may contain absolutely catastrophic deal-breaker bugs. Thank you very much
for the testing efforts 💗`,
	Example: "  abra upgrade --rc",
	Args:    cobra.NoArgs,
	Run: func(cmd *cobra.Command, args []string) {
		mainURL := "https://install.abra.coopcloud.tech"
		c := exec.Command("bash", "-c", fmt.Sprintf("wget -q -O- %s | bash", mainURL))

		if releaseCandidate {
			releaseCandidateURL := "https://git.coopcloud.tech/coop-cloud/abra/raw/branch/main/scripts/installer/installer"
			c = exec.Command("bash", "-c", fmt.Sprintf("wget -q -O- %s | bash -s -- --rc", releaseCandidateURL))
		}

		log.Debugf("attempting to run %s", c)

		if err := internal.RunCmd(c); err != nil {
			log.Fatal(err)
		}
	},
}

var (
	releaseCandidate bool
)

func init() {
	UpgradeCommand.Flags().BoolVarP(
		&releaseCandidate,
		"rc",
		"r",
		false,
		"install release candidate (may contain bugs)",
	)
}