use std::process::Command;

use anyhow::{Context, Result, bail};

use crate::cli::Site;
use crate::commands::site;

pub async fn run(site: Site) -> Result<()> {
    match site {
        Site::DevOllaFr => {
            site::build::run(site)?;
            tailwind_prod(site)?;
            rsync(site)?;
        }
    }

    Ok(())
}

fn tailwind_prod(site: Site) -> Result<()> {
    let status = Command::new("npx")
        .args([
            "@tailwindcss/cli",
            "-i",
            "content/css/app.css",
            "-o",
            &format!("{}/css/app.css", site.build_dir()),
            "--minify",
        ])
        .status()
        .context("impossible de lancer npx tailwindcss")?;

    if !status.success() {
        bail!("tailwind build a échoué");
    }

    Ok(())
}

fn rsync(site: Site) -> Result<()> {
    let build_dir = format!("{}/", site.build_dir());

    let status = Command::new("rsync")
        .args(["-Pr", "--delete", &build_dir, site.deploy_target()])
        .status()
        .context("impossible de lancer rsync")?;

    if !status.success() {
        bail!("rsync a échoué");
    }

    Ok(())
}
