#!/usr/bin/env nu
# Generates .cargo/config.toml from config.base.toml + machine-local settings.
# Run once after cloning, and again any time you mount/remount /Volumes/Devel.

def main [
    --project: string = "ontoref"   # project name (sets /Volumes/Devel/<project>/target)
    --sccache-size: string = "30G"  # sccache cache size limit
    --dry-run                        # print generated config without writing
] {
    let base = ".cargo/config.base.toml"
    let out  = ".cargo/config.toml"
    let sentinel = "/Volumes/Devel/.volume-ok"

    if not ($base | path exists) {
        error make { msg: $"base config not found: ($base) — is this run from the project root?" }
    }

    let base_content = open --raw $base

    let local_section = if ($sentinel | path exists) {
        let target_dir  = $"/Volumes/Devel/($project)/target"
        let sccache_dir = "/Volumes/Devel/sccache"

        mkdir $target_dir
        mkdir $sccache_dir

        let has_sccache = (which sccache | length) > 0

        let wrapper_line = if $has_sccache {
            "rustc-wrapper = \"sccache\""
        } else {
            "# rustc-wrapper = \"sccache\"  # install sccache to enable: cargo install sccache"
        }

        [
            ""
            "# --- machine-local (generated by install/setup-dev.nu) ---"
            "# /Volumes/Devel is mounted — using external volume for build artifacts."
            ""
            "[build]"
            $"target-dir   = \"($target_dir)\""
            $wrapper_line
            ""
            "[env]"
            $"SCCACHE_DIR        = \"($sccache_dir)\""
            $"SCCACHE_CACHE_SIZE = \"($sccache_size)\""
        ] | str join "\n"
    } else {
        print $"warning: /Volumes/Devel not mounted \(sentinel ($sentinel) missing\)"
        print "         target-dir not set — builds will use ./target"
        print "         Mount the volume and re-run this script to enable external target dir."
        [
            ""
            "# --- machine-local (generated by install/setup-dev.nu) ---"
            "# /Volumes/Devel NOT mounted — using local ./target."
            "# Mount volume and run `just setup-dev` to redirect builds to /Volumes/Devel."
        ] | str join "\n"
    }

    let generated = $"($base_content)\n($local_section)\n"

    if $dry_run {
        print $generated
    } else {
        $generated | save --force $out
        print $"wrote ($out)"
        if ($sentinel | path exists) {
            print $"  target-dir  = /Volumes/Devel/($project)/target"
            print $"  SCCACHE_DIR = /Volumes/Devel/sccache"
            if (which sccache | length) > 0 {
                print "  rustc-wrapper = sccache ✓"
            } else {
                print "  rustc-wrapper = (sccache not installed — skipped)"
            }
        }
    }
}
