use crate::get_global_args;
use crate::io::print_items;
use std::{io, process::Command};

fn make_apt_get() -> Command {
    let mut cmd = Command::new("apt-get");

    if get_global_args().non_interactive {
        cmd.arg("--yes");
    }

    cmd
}

pub fn does_package_exist(name: &str) -> io::Result<bool> {
    let output = Command::new("apt-cache")
        .arg("search")
        .arg(format!("^{}$", name))
        .output()?;

    let output_text = String::from_utf8(output.stdout).unwrap();
    Ok(output_text.contains("\n"))
}

pub fn install_packages(names: &Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
    print!("Installing packages: ");
    print_items(names);

    let status = make_apt_get().arg("install").args(names).status()?;

    if !status.success() {
        return Err("Failed to install packages.".into());
    }

    Ok(())
}

pub fn purge_prefix(prefix: &str) -> Result<(), Box<dyn std::error::Error>> {
    let status = make_apt_get()
        .arg("purge")
        .arg(format!("{}*", prefix))
        .status()?;

    if !status.success() {
        return Err("Failed to purge packages.".into());
    }

    Ok(())
}
