#!/usr/bin/env -S deno run --allow-all
const { run, Timeout, Env, Cwd, Stdin, Stdout, Stderr, Out, Overwrite, AppendTo, zipInto, mergeInto, returnAsString, } = await import(`https://deno.land/x/sprinter@0.3.2/index.js`)
const { FileSystem, Console } = await import(`https://deno.land/x/file_system_js@0.0.7/main/deno.js`)

// 
// args
// 
let [ url, branch, commit ] = Deno.args

// 
// interactive 
// 
if (!url) {
    url = Console.askFor.line("What is the url to the mixin?")
}

if (!branch) {
    brach = Console.askFor.line("What is the branch you want to mixin? (default=master)")
    if (!branch) {
        branch = "master"
    }
}

// 
// 
// actual logic
// 
// 
async function mixin(url, branch, commit, specialBranchName="@__mixin__") {
    const { run, Timeout, Env, Cwd, Stdin, Stdout, Stderr, Out, Overwrite, AppendTo, zipInto, mergeInto, returnAsString, } = await import(`https://deno.land/x/sprinter@0.3.2/index.js`)
    const { FileSystem, Console } = await import(`https://deno.land/x/file_system_js@0.0.7/main/deno.js`)

    // remove any leftover ones (caused by git merge conflicts)
    await run("git", "remote", "remove", specialBranchName, Out(null)) // git remote remove __mixin__ &>/dev/null
    await run("git", "remote", "add", specialBranchName, url)          // git remote add __mixin__ "$url"
    await run("git", "fetch", specialBranchName, url)                  // git fetch __mixin__ "$branch"

    // if there was a commit
    if (commit) {
        // only merge the one commit
        await run("git", "cherry-pick", commit) // git cherry-pick "$commit"
    // otherwise merge everything
    } else {
        await run("git", "pull", "--allow-unrelated-histories", specialBranchName, branch)
    }

    // update submodules (probably not the best behavior for super-large repos with optional submodules)
    await run("git", "submodule", "update", "--init", "--recursive")
    // clean up afterwords
    await run("git", "remote", "remove", specialBranchName, Out(null)) // git remote remove __mixin__ &>/dev/null
}

// 
// run it
// 
mixin(url, branch, commit)