#!/usr/bin/env bash

JUL_MIRROR="https://github.com/JuliaLang/julia"


# Output lists of versions
plug_list_versions() {
    echo $(curl -s "$JUL_MIRROR/releases/" | \
        grep "releases/tag" | \
        grep -E -o '\/v[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)*' | \
        sed 's/\/v//g' | sort)
}

# Plugin installation logic
plug_install() {
    local plugin_name=$1
    local version=$2
    local env_name_full=$3

    # execute in subshell
    (
        local arc_path=$(nv_get_arc_path "$plugin_name" "$version")

        # clone
        if [ ! -d "$arc_path" ]; then
            git clone "${JUL_MIRROR}.git" "$arc_path"
        fi

        # compiling (if need)
        if [ ! -f "$arc_path/usr/bin/julia-readline" ] &&
            [ ! -f "$arc_path/usr/bin/julia" ]; then
            cd "$arc_path"
            git checkout v${version}
            make -j $(nv_get_cpu_count) || {
                echo 'envirius: make failed!' ;
                return 1;
            }
        fi

        # copy bin into new environment
        # mkdir -p "$env_name_full/bin"
        cp -r "$arc_path/usr"/* "$env_name_full"
        if [ ! -e "$env_name_full/bin/julia" ]; then
            if [ -e "$env_name_full/bin/julia-readline" ]; then
                ln -s "$env_name_full/bin/julia-readline" \
                        "$env_name_full/bin/julia"
            else
                echo "envirius: something went wrong! julia not found!"
                return 1
            fi
        fi
    )
}
