//! `cachedir` is a tiny utility for tagging, finding, and untagging
//! directories as cache directories, according to the
//! <http://www.bford.info/cachedir/> specification.
//!
//! ~~~sh
//! $ cachedir find $HOME
//! $ cachedir tag $HOME/.cache
//! $ cachedir find $HOME
//! /home/liw/.cache
//! $ cachedir untag $HOME/.cache
//! $ cachedir find $HOME
//! $
//! ~~~

use cachedir::{is_cachedir_tag, CacheDirError, CACHEDIR_TAG, TAG};
use clap::{Parser, Subcommand};
use std::error::Error;
use std::fs::{remove_file, write};
use std::path::PathBuf;
use walkdir::{DirEntry, WalkDir};

/// The main program.
fn main() {
    if let Err(e) = real_main() {
        eprintln!("ERROR: {e}");

        let mut e = e.source();
        while let Some(err) = e {
            eprintln!("caused by: {err}");
            e = err.source();
        }

        std::process::exit(1);
    }
}

/// Fallible main program.
fn real_main() -> Result<(), CacheDirError> {
    let args = Args::parse();
    match args.cmd {
        Command::Find { dirs } => walk(&dirs, find),
        Command::Tag { dirs } => walk(&dirs, tag),
        Command::Untag { dirs } => walk(&dirs, untag),
        Command::IsCache { dir } => is_cache(dir),
    }
}

/// Command line arguments.
#[derive(Debug, Parser)]
struct Args {
    #[clap(subcommand)]
    cmd: Command,
}

/// Subcommands.
#[derive(Debug, Subcommand)]
enum Command {
    /// Find cache directories starting at given directories.
    Find { dirs: Vec<PathBuf> },
    /// Add cache directory tag to given directories.
    Tag { dirs: Vec<PathBuf> },
    /// Remove cache directory tag from given directories.
    Untag { dirs: Vec<PathBuf> },
    /// Is the single given directory tagged as a cache directory?
    IsCache { dir: PathBuf },
}

/// Is the given directory a cache?
fn is_cache(dir: PathBuf) -> Result<(), CacheDirError> {
    let filename = dir.join(CACHEDIR_TAG);
    if !is_cachedir_tag(&filename)? {
        std::process::exit(1);
    }
    Ok(())
}

/// Is the given directory a cache?
fn find(entry: &DirEntry) -> Result<(), CacheDirError> {
    let filename = tag_filename(entry);
    if is_cachedir_tag(&filename)? {
        println!("{}", entry.path().display());
    }
    Ok(())
}

/// Add a tag file to the given directory.
fn tag(entry: &DirEntry) -> Result<(), CacheDirError> {
    let filename = tag_filename(entry);
    if !is_cachedir_tag(&filename)? {
        write(&filename, TAG).map_err(|e| CacheDirError::Write(filename.clone(), e))?;
    }
    Ok(())
}

/// Remove a tag file from the given directory.
fn untag(entry: &DirEntry) -> Result<(), CacheDirError> {
    let filename = tag_filename(entry);
    if is_cachedir_tag(&filename)? {
        remove_file(&filename).map_err(|e| CacheDirError::Remove(filename.clone(), e))?;
    }
    Ok(())
}

/// Iterate over all directories, call given function for each.
fn walk<F>(dirs: &[PathBuf], mut func: F) -> Result<(), CacheDirError>
where
    F: FnMut(&DirEntry) -> Result<(), CacheDirError>,
{
    for dir in dirs {
        for entry in WalkDir::new(dir) {
            let entry = entry.map_err(CacheDirError::WalkDir)?;
            if entry.metadata()?.is_dir() {
                func(&entry)?;
            }
        }
    }
    Ok(())
}

/// Return path to tag file in a directory.
fn tag_filename(entry: &DirEntry) -> PathBuf {
    entry.path().join(CACHEDIR_TAG)
}
