/*
Copyright © 2024 Mark Bailey <gitea.com/cerbervs>
This file is part of a CLI application developed by Mark Bailey
*/
package cmd

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"

	"github.com/spf13/cobra"
)

var (
	// Flags
	IgnoreUpgrade bool
	Version       string

	// Args
	PkgName string
)

var rootCmd = &cobra.Command{
	Use:   "flatpak-downgrade",
	Short: "Used to downgrade flatpak applications to a previous version.",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		PkgName = args[0]

		if Version == "" {
			Version = GetPreviousVersion(PkgName)
		}

		downgrade()
	},
}

func downgrade() {
	fmt.Println("Downgrading ", PkgName, "to ", Version)

	cmd := exec.Command("flatpak", "update", "--commit="+Version, PkgName)

	outpipe, _ := cmd.StdoutPipe()
	defer outpipe.Close()
	scanner := bufio.NewScanner(outpipe)

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Start()
	if err != nil {
		log.Fatal("Start Error: ", "\nPlease try running with root privileges.")
		panic(err)
	}

	var text string
	for scanner.Scan() {
		text = scanner.Text() + text
		if strings.Contains(scanner.Text(), "Nothing to do.") {
			os.Exit(0)
		}
	}

	fmt.Println("Text was: " + text)

	if IgnoreUpgrade {
		mask()
	}

	fmt.Println("Downgrade successful!")
	os.Exit(0)
}

func mask() {
	mask := exec.Command("flatpak", "mask", PkgName)
	maskErr := mask.Run()
	if maskErr != nil {
		log.Fatal("Error: ", maskErr, "\nPlease try running with root privileges.")
	} else {
		fmt.Println("Marked ", PkgName, " as ignored for upgrade.")
	}
}

func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.Flags().BoolVarP(&IgnoreUpgrade, "ignore-upgrage", "i", false, "Mark flatpak as ignored for upgrade")
	rootCmd.Flags().StringVarP(&Version, "version", "v", "", "Commit hash of the specific version")
}
