#!/bin/bash

"""
This is a utility script which uninstalls STIR by removing all created binaries
and library files. 

__There is NO GUARANTEE that this will work.

Binaries and libraries are automatically detected based on the output of
`make install`. However, this only works if `make install` was run successfully
before.
"""

DIR_BUILD_STIR="STIR_build"

if [ -z ${VIRTUAL_ENV} ]; then
    INSTALL_PREFIX="/usr/local"
else
    INSTALL_PREFIX=${VIRTUAL_ENV}
fi

DIR_STIR_BIN="${INSTALL_PREFIX}/bin"
DIR_STIR_LIB="${INSTALL_PREFIX}/lib"
FILE_MAKE_OUT="make_output.txt"

cd ${DIR_BUILD_STIR} && \
make install > ${FILE_MAKE_OUT} && \
cd -

STIR_BINS=$(cat ${DIR_BUILD_STIR}/${FILE_MAKE_OUT} | grep "bin/" | sed "s/bin\//%/g" | cut -d "%" -f 2)
STIR_LIBS=$(cat ${DIR_BUILD_STIR}/${FILE_MAKE_OUT} | grep "lib/" | sed "s/lib\//%/g" | cut -d "%" -f 2)

echo "================================================"
echo "Remove STIR binaries:"
for STIR_BIN in ${STIR_BINS}; do
    echo "sudo rm ${DIR_STIR_BIN}/${STIR_BIN}"
done
read -p "Are you sure? (y/n)" -n 1 -r
echo
if [[ ${REPLY} == "y" ]]; then
    echo "Remove STIR binaries!"
    for STIR_BIN in ${STIR_BINS}; do
        sudo rm ${DIR_STIR_BIN}/${STIR_BIN}
    done
fi

echo 
echo "Remove STIR libraries:"
for STIR_LIB in ${STIR_LIBS}; do
    echo "sudo rm ${DIR_STIR_LIB}/${STIR_LIB}"
done
read -p "Are you sure? (y/n)" -n 1 -r
echo
if [[ ${REPLY} == "y" ]]; then
    echo "Remove STIR libraries!"
    for STIR_LIB in ${STIR_LIBS}; do
        sudo rm ${DIR_STIR_LIB}/${STIR_LIB}
    done
fi

rm ${DIR_BUILD_STIR}/${FILE_MAKE_OUT}