package main

import (
	"os/exec"
	"strings"
)

type InstallPlan struct {
	ManagerName string
	Command     []string
}

func (p InstallPlan) DisplayCommand() string {
	return strings.Join(p.Command, " ")
}

func execLookPath(file string) (string, error) {
	return exec.LookPath(file)
}

func DetectSambaInstallPlan(lookPath LookPathFunc, isRoot bool) (InstallPlan, bool) {
	sudoPrefix := []string{}
	if !isRoot {
		if _, err := lookPath("sudo"); err == nil {
			sudoPrefix = []string{"sudo"}
		}
	}

	plans := []struct {
		bin     string
		name    string
		command []string
	}{
		{bin: "apt-get", name: "apt", command: []string{"apt-get", "update"}},
		{bin: "apt-get", name: "apt", command: []string{"apt-get", "install", "-y", "samba"}},
		{bin: "dnf", name: "dnf", command: []string{"dnf", "install", "-y", "samba"}},
		{bin: "yum", name: "yum", command: []string{"yum", "install", "-y", "samba"}},
		{bin: "pacman", name: "pacman", command: []string{"pacman", "-Sy", "--noconfirm", "samba"}},
		{bin: "zypper", name: "zypper", command: []string{"zypper", "--non-interactive", "install", "samba"}},
		{bin: "apk", name: "apk", command: []string{"apk", "add", "samba"}},
	}

	if _, err := lookPath("apt-get"); err == nil {
		return InstallPlan{
			ManagerName: "apt",
			Command: append(
				append([]string{}, sudoPrefix...),
				"sh", "-c", "apt-get update && apt-get install -y samba",
			),
		}, true
	}

	for _, plan := range plans[2:] {
		if _, err := lookPath(plan.bin); err == nil {
			return InstallPlan{
				ManagerName: plan.name,
				Command:     append(append([]string{}, sudoPrefix...), plan.command...),
			}, true
		}
	}

	return InstallPlan{}, false
}

func DetectCIFSUtilsInstallPlan(lookPath LookPathFunc, isRoot bool) (InstallPlan, bool) {
	sudoPrefix := []string{}
	if !isRoot {
		if _, err := lookPath("sudo"); err == nil {
			sudoPrefix = []string{"sudo"}
		}
	}

	type managerPlan struct {
		bin     string
		name    string
		command []string
	}

	plans := []managerPlan{
		{bin: "dnf", name: "dnf", command: []string{"dnf", "install", "-y", "cifs-utils"}},
		{bin: "yum", name: "yum", command: []string{"yum", "install", "-y", "cifs-utils"}},
		{bin: "pacman", name: "pacman", command: []string{"pacman", "-Sy", "--noconfirm", "cifs-utils"}},
		{bin: "zypper", name: "zypper", command: []string{"zypper", "--non-interactive", "install", "cifs-utils"}},
		{bin: "apk", name: "apk", command: []string{"apk", "add", "cifs-utils"}},
	}

	if _, err := lookPath("apt-get"); err == nil {
		return InstallPlan{
			ManagerName: "apt",
			Command: append(
				append([]string{}, sudoPrefix...),
				"sh", "-c", "apt-get update && apt-get install -y cifs-utils",
			),
		}, true
	}

	for _, plan := range plans {
		if _, err := lookPath(plan.bin); err == nil {
			return InstallPlan{
				ManagerName: plan.name,
				Command:     append(append([]string{}, sudoPrefix...), plan.command...),
			}, true
		}
	}

	return InstallPlan{}, false
}
