use serde::Deserialize;
use std::process::Command;

fn main() {
    // trigger recompilation when a new migration is added
    println!("cargo:rerun-if-changed=migrations");

    let target = get_swift_target_info();
    if target.target.unversioned_triple.contains("linux") {
        target.paths.runtime_library_paths.iter().for_each(|path| {
            println!("cargo:rustc-link-arg=-Wl,-rpath={}", path);
        });

        let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
        println!(
            "cargo:rustc-link-arg={}/linux/{}/swiftrt.o",
            &target.paths.runtime_resource_path, arch
        );
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SwiftTargetInfo {
    pub unversioned_triple: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SwiftPaths {
    pub runtime_library_paths: Vec<String>,
    pub runtime_resource_path: String,
}

#[derive(Debug, Deserialize)]
pub struct SwiftTarget {
    pub target: SwiftTargetInfo,
    pub paths: SwiftPaths,
}

pub fn get_swift_target_info() -> SwiftTarget {
    let swift_target_info_str = Command::new("swift")
        .args(&["-print-target-info"])
        .output()
        .unwrap()
        .stdout;

    serde_json::from_slice(&swift_target_info_str).unwrap()
}
