#!/bin/bash

set -euo pipefail

switch_to_pkg() {
    for dep in $(cue export -e deps cue.mod/module.cue | yq -o tsv '. | keys'); do
        name=$(echo "$dep" | cut -d@ -f1)
        dir=$(dirname "$name")
        mod=$(basename "$name")
        mkdir -vp "cue.mod/pkg/$dir"
        cd "cue.mod/pkg/$dir"
        ln -vs "$moduledir/$mod" .
        cd "$startdir"
        cue mod edit --drop-require "$dep"
    done
    echo "done"
}

switch_to_registry() {
    rm -rfv cue.mod/pkg
    echo "cue mod tidy"
    cue mod tidy
    echo "done"
}

main() {
    moduledir=/home/mlangner/workspace/cue-workspace/publish
    startdir=$PWD

    if [[ ! -d cue.mod ]]; then
        echo "cue.mod not found"
        exit
    fi

    if [[ ! -d "$moduledir/libmcs" ]]; then
        echo "moduledir/libmcs not found"
        exit
    fi

    if [[ -d cue.mod/pkg ]]; then
        echo "switch to registry"
        switch_to_registry
        exit
    else
        echo "switch to pkg"
        switch_to_pkg
        exit
    fi
}

main
