use std::fs::{read_dir, File};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use permissions::is_executable;

fn main() {
    println!("Building started...");
    println!("Installing git hooks...");
    if !Path::new(".git/hooks").exists() {
        return;
    }
    let hooks_dir = read_dir(Path::new(".hooks")).unwrap();
    let mut hook_files: Vec<String> = Vec::new();
    hooks_dir.for_each(|file| {
        if file.is_ok() {
            let file = file.unwrap();
            let path = file.path();
            let file_name = file.file_name();
            let new_path = Path::new(".git/hooks").join(file_name);
            hook_files.push(new_path.to_str().unwrap().to_string());
            std::fs::copy(path.clone(), new_path).unwrap();
        }
    });
    println!("Hooks created...");
    println!("Checking hooks permissions...");
    hook_files.iter().for_each(|file_path| {
        let file = File::open(Path::new(file_path)).unwrap();
        let mut permissions = file.metadata().unwrap().permissions();
        permissions.set_mode(0o751);
        if !is_executable(file_path).unwrap() {
            file.set_permissions(permissions).unwrap();
        }
    });
    println!("Hooks installed correctly!");
}