package cmd

import (
	"fmt"
	"os"
	"os/exec"

	"github.com/spf13/cobra"
)

var installCmd = &cobra.Command{
	Use:   "install",
	Short: "installs a package",
	Long:  `installs a package from the aur to the system.`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			fmt.Fprintln(os.Stderr, "error: package name required")
			return
		}
		pkg := args[0]
		url := "https://aur.archlinux.org/" + pkg

		// git clone
		fmt.Println("cloning:", url)
		out, err := exec.Command("git", "clone", url).CombinedOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "git clone failed: %v\n%s\n", err, string(out))
			return
		}

		// makepkg -si inside package dir
		fmt.Println("building/installing:", pkg)
		buildCmd := exec.Command("makepkg", "-si", "--noconfirm")
		buildCmd.Dir = pkg
		buildCmd.Stdin = os.Stdin
		buildCmd.Stdout = os.Stdout
		buildCmd.Stderr = os.Stderr
		buildCmd.Run()
		// cleanup
		if err := os.RemoveAll(pkg); err != nil {
			fmt.Fprintf(os.Stderr, "warning: failed to remove %s: %v\n", pkg, err)
		}

		fmt.Println("install successful")
	},
}

func init() {
	rootCmd.AddCommand(installCmd)
}

