use std::env;
use std::fs::File;
use std::io::prelude::*;

#[cfg(unix)]
use std::os::unix::fs::symlink;

#[cfg(all(windows, not(target_env = "msvc")))]
use std::os::windows::fs::symlink_file as symlink;

#[cfg(not(target_env = "msvc"))]
use std::fs;
#[cfg(not(target_env = "msvc"))]
use std::path::PathBuf;

fn main() {
    generate_convenience_lib().unwrap();
}

/// Generate libtool archive file librsvg_c_api.la
/// From: https://docs.rs/libtool/0.1.1/libtool/
#[cfg(not(target_env = "msvc"))]
pub fn generate_convenience_lib() -> std::io::Result<()> {
    let target = env::var("TARGET").expect("TARGET was not set");
    let build_dir = env::var("LIBRSVG_BUILD_DIR").expect("LIBRSVG_BUILD_DIR was not set");
    let target_dir = env::var("LIBRSVG_TARGET_DIR").expect("LIBRSVG_TARGET_DIR was not set");
    let libs_dir = format!("{}/.libs", build_dir);
    let libs_path = PathBuf::from(&libs_dir);
    let la_path = PathBuf::from(format!("{}/librsvg_c_api.la", build_dir));
    let rust_lib = if target.contains("windows") {
        /* https://github.com/rust-lang/rust/issues/43749 */
        "rsvg_c_api.lib"
    } else {
        "librsvg_c_api.a"
    };
    let old_lib_path = PathBuf::from(format!("{}/{}", target_dir, rust_lib));
    let new_lib_path = PathBuf::from(format!("{}/librsvg_c_api.a", libs_dir));

    match fs::create_dir_all(&libs_path) {
        Ok(()) => println!("libs_path created"),
        _ => panic!("Failed to create libs_path"),
    }

    if la_path.exists() {
        fs::remove_file(&la_path)?;
    }

    /* PathBuf.exists() traverses symlinks so just try and remove it */
    match fs::remove_file(&new_lib_path) {
        Ok(_v) => {},
        Err(e) => println!("Error removing symlink: {:?}", e),
    }

    let mut file = File::create(&la_path).unwrap();
    writeln!(file, "# librsvg_c_api.la - a libtool library file")?;
    writeln!(file, "# Generated by libtool-rust")?;
    writeln!(file, "dlname=''")?;
    writeln!(file, "library_names=''")?;
    writeln!(file, "old_library='librsvg_c_api.a'")?;
    writeln!(file, "inherited_linker_flags=''")?;
    writeln!(file, "installed=no")?;
    writeln!(file, "shouldnotlink=no")?;
    symlink(&old_lib_path, &new_lib_path)?;
    Ok(())
}

#[cfg(target_env = "msvc")]
pub fn generate_convenience_lib() -> std::io::Result<()> {
    Ok(())
}
