#!/usr/bin/env bash

NODE_MIRROR="http://nodejs.org/dist"
BIN_PREFIX="node"

# Output lists of versions
plug_list_versions() {
    echo $(curl -s "$NODE_MIRROR/" | \
                grep -v "node-" | \
                egrep -o '[0-9]+\.[0-9]+\.[0-9]+' | \
                sort -u -k 1,1n -k 2,2n -k 3,3n -t .)
}

# Return full url for tarball for download
# and future installation
#
# Input:
#   $1 — version for installation
plug_url_for_download() {
    local version=$1
    echo "$NODE_MIRROR/v${version}/${BIN_PREFIX}-v${version}.tar.gz"
}

# Fix paths in shabangs
plug_post_install_actions() {
    local env_name=$1
    local env_name_full=$2
    local plugin_ver=$3
    local build_path=$(nv_get_build_path "node" "$plugin_ver")

    # replace in files build path to the env path
    # files:
    # - env/lib/node_modules/npm/bin/npm-cli.js
    # - env/include/node/config.gypi
    for f in $(find "$env_name_full" -type f -iname "*.*" -print0 | \
                    xargs -0 grep -i "$build_path" | \
                    cut -d ':' -f 1); do
        sed -i "s|$build_path|$env_name_full|g" $f
    done
}
