#!/usr/bin/env bash

# Columns count in the version's grid
plug_list_versions_columns_count=6

# Column's width in characters in the version's grid
plug_list_versions_columns_size=10

ERL_MIRROR="http://erlang.org/download/"

# Output lists of versions
plug_list_versions() {
    echo $(curl -s $ERL_MIRROR | \
        egrep -o '\/download\/otp_src_(R1[-0-9A-Za-z_]+)\.tar\.gz' | \
        egrep -o 'otp_src_R1[-0-9A-Za-z]+' | \
        egrep -o 'R1[-0-9A-Za-z]+')
    echo $(curl -s $ERL_MIRROR | \
        egrep -o "otp_src_[0-9]+\.[0-9]+(-rc[0-9]+)*\.tar\.gz" | \
        egrep -o "[0-9]+\.[0-9]+(-rc[0-9]+)*" | sort | uniq | \
        sort --reverse)
}

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

# Install rebar
plug_post_install_actions() {
    local env_name=$1
    local env_name_full=$2
    if [ ! -f "$env_name_full/bin/rebar" ]; then
    (
        local rebar_path=$(nv_get_cache_full_path "rebar")
        if [ ! -d "$rebar_path" ]; then
            cd $(nv_get_cache_full_path)
            git clone git://github.com/rebar/rebar.git >/dev/null
        fi
        nv on --same-shell $env_name >/dev/null
        cd $rebar_path
        ./bootstrap >/dev/null
        cp $rebar_path/rebar $env_name_full/bin
        nv off >/dev/null
    )
    fi
}
