#!/usr/bin/env bash

set -euo pipefail

LIBDIR=$PWD/libraries
VERSIONED_GHCS=$1
PRIMARY_GHC_VERS=$2

unversion() {
    echo $1 | sed 's/-[0-9.]*$//'
}

# versioned GHCs
for i in "$VERSIONED_GHCS/*"; do
    SRCDIR=$i/libraries
    for F in $SRCDIR/*; do
        ln -sf $(readlink -f $F) $LIBDIR/$(basename $F)
    done
done

# shorthands for the primary (base → base-?.?.?.?)
for F in $VERSIONED_GHCS/$PRIMARY_GHC_VERS/libraries/*; do
    if [[ -d $F ]]; then
        ln -sf $(basename $F) $LIBDIR/$(unversion $(basename $F))
    else
        ln -sf $(readlink -f $F) $LIBDIR/$(basename $F)
    fi
done

# pull cabalized packages in here too
for CABALIZED in $(find  ~/.cabal/store/ghc-$PRIMARY_GHC_VERS -path '**/share/doc/html'); do
    NICE_NAME=$(basename $(readlink -f $CABALIZED/../../..) | sed 's/-[0-9a-F]*$//')
    ln -sf $CABALIZED $LIBDIR/$NICE_NAME
    ln -sf $NICE_NAME $LIBDIR/$(unversion $NICE_NAME)
done
