system_setup_tool/pkg/packagemanager/apt.go

81 lines
2.1 KiB
Go

package packagemanager
import (
"fmt"
"log"
"strings"
"system_setup_tool/internal/shell"
)
type AptManager struct {
SudoPassword string
}
func (a *AptManager) Install(packages []string) error {
if len(packages) == 0 {
return nil
}
err := InstallWithProgress(a, packages)
if err != nil {
return err
}
return nil
}
func (a *AptManager) Name() string {
return "OS Home Manager"
}
func (a *AptManager) InstallManager() error {
return nil
}
func (a *AptManager) InstallPackage(pkg string) error {
cmd := "apt install -y"
fullCmd := fmt.Sprintf("%s %s", cmd, pkg)
command := shell.ExecCommand("sudo", "-S", "sh", "-c", fullCmd)
command.Stdin = strings.NewReader(a.SudoPassword + "\n")
return command.Run()
}
func (a *AptManager) RemovePackage(pkg string) error {
cmd := "apt remove -y"
fullCmd := fmt.Sprintf("%s %s", cmd, pkg)
command := shell.ExecCommand("sudo", "-S", "sh", "-c", fullCmd)
command.Stdin = strings.NewReader(a.SudoPassword + "\n")
return command.Run()
}
func (a *AptManager) SearchPackage(pkg string) []string {
cmd := "apt search -y"
fullCmd := fmt.Sprintf("%s %s", cmd, pkg)
command := shell.ExecCommand("sudo", "-S", "sh", "-c", fullCmd)
command.Stdin = strings.NewReader(a.SudoPassword + "\n")
packages, err := command.Output()
if err != nil {
log.Printf("error fetching %s packages: %v", a.Name(), err)
}
packageList := strings.Split(strings.TrimSpace(string(packages)), "\n")
return packageList
}
func (a *AptManager) UpdatePackage(pkg string) error {
cmd := "apt update -y"
fullCmd := fmt.Sprintf("%s %s", cmd, pkg)
command := shell.ExecCommand("sudo", "-S", "sh", "-c", fullCmd)
command.Stdin = strings.NewReader(a.SudoPassword + "\n")
return command.Run()
}
func (a *AptManager) UpdateAllPackages() error {
cmd := "apt update -y"
fullCmd := fmt.Sprintf("%s", cmd)
command := shell.ExecCommand("sudo", "-S", "sh", "-c", fullCmd)
command.Stdin = strings.NewReader(a.SudoPassword + "\n")
return command.Run()
}
func (a *AptManager) Check(pkg string) error {
cmd := shell.ExecCommand("/bin/sh", "-c", fmt.Sprintf("dpkg -l | grep %s", pkg))
return cmd.Run()
}