#!/usr/bin/env bash
set -e

# This script generates "manifest.remap"
# from a specified server.
#
# command line:
#    generate-remap.sh  PRODUCT-VERSION... BUILDFILE_DIR...

enumerateProducts()
{
    for arg in "$@"
    do
        if [[ -d "$arg" ]]
        then
            while read -r buildfile
            do
                echo "$(basename "${buildfile%.build}")"
            done <<< "$(find "$arg" -name "*.build")"
        else
            echo "${arg%.build}"
        fi
    done
}


alignColumns()
{
    local cols1=()
    local cols2=()
    local max_col1=0

    local col1 col2
    while read -r col1 col2
    do
        cols1+=("$col1")
        cols2+=("$col2")

        if [[ max_col1 -lt "${#col1}" ]]
        then
            max_col1="${#col1}"
        fi
    done

    local spaces="$(spaces $max_col1)"

    local i
    for((i = 0; i < ${#cols1[@]}; ++i))
    do
        col1="${cols1[i]}$spaces"
        col2="${cols2[i]}"

        echo "${col1:0:max_col1}  ${col2}"
    done
}


spaces()
{
    local n="$1"
    local i
    for((i = 0; i < n; ++i))
    do
        echo -n ' '
    done

    echo ''
}


addHeader()
{
    cat << 'EOF'
# Copy this file into ~/.eups if you want to install another versions of
# packages with 'eups install'. If you don't understand what it means,
# you must never do that copy.
#
# One thing you must bear in mind:
# If you execute 'eups install', we the binary distributor will stop
# providing support to you, if any, since we cannot know the state of your
# $EUPS_PATH in that case. Do it AT YOUR OWN RISK.
#
EOF
    cat
}


enumerateProducts "$@" |
    sed -n '/-/ { s/-/ / ; p }' |
    sort |
    alignColumns |
    addHeader
