#!/usr/bin/env bash

ELX_MIRROR="https://github.com/elixir-lang/elixir"


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

# Plugin installation logic.
#
# Input:
#   $1 — plugin name (erlang, rust, ...)
#   $2 — plugin version
#   $3 — full path to the environment
plug_install() {
    local plugin_name=$1
    local version=$2
    local env_name_full=$3

    local tarball=$(nv_download_file "$ELX_MIRROR/archive/v${version}.tar.gz" \
                "${plugin_name}-${version}.tar.gz")
    # execute in subshell
    (
        local src_path=$(nv_get_src_path "$plugin_name" "$version")

        # unpacking (if need)
        if [ ! -d "$src_path" ]; then
            mkdir -p "$src_path"
            tar -xzf "$tarball" -C "$src_path"
        fi

        # compiling
        cd "$src_path"
        local subdir=$(find . -mindepth 1 -maxdepth 1 -type d)
        cd "$subdir"
        make

        # copy all bins into new environment
        cp -r "$src_path/$subdir"/bin $env_name_full
        cp -r "$src_path/$subdir"/lib $env_name_full
    )
}
