#!/usr/bin/env bash

# Remove script for sifdecode
# version for Bourne/bash shell

# syntax: uninstall_sifdecode

# N. Gould, D. Orban & Ph. Toint
# ( Last modified on 20 October 2012 at 11:00 GMT )

#  check input arguments (if any)

if [[ $# != 0 ]]; then
   echo "Use: uninstall_sifdecode"
   exit 1
fi

export SIFDECODE=`dirs -l`
export SIFDECODE=`echo $SIFDECODE | \sed 's"/tmp_mnt""'`

. $SIFDECODE/bin/sifdecode_envcheck

finished='false'
while [[ $finished != 'true' ]]; do

#   VERS=( `\ls $SIFDECODE/versions/*` )
    VERS=( `\ls $SIFDECODE/versions/* 2>/dev/null` )
    NUMBER=${#VERS[@]}

    if [[ $NUMBER == 0 ]]; then
        warning "No versions of SIFDECODE are currently installed."
        exit 1
    fi

    LIST=( ${VERS[@]} )

    CORRECT_VERSION="false"
    while [[ $CORRECT_VERSION == "false" ]]; do

    echo -e " The following versions of SIFDECODE are currently installed.\n"
    count=0
    for i  in  ${LIST[@]}; do
        (( count++ ))
        (( cnt = count-1 )) # 0-based indexing
        VERSION="`cat ${VERS[$cnt]}`"
        echo "        ($count) ${VERSION}"
    done
    echo -e "\n Which do you wish to uninstall: (1-$NUMBER)?"

    read CHOICE
    (( CHOICE-- ))

    i=0
    while [[ $i -lt $NUMBER &&  $CORRECT_VERSION == "false" ]]; do
        if [[ $CHOICE == $i ]]; then
        CORRECT_VERSION="true"
        CHOICE=$i
        fi
        (( i++ ))
    done
    if [[ $CORRECT_VERSION == "true" ]]; then
        VERSION=${VERS[$CHOICE]##*/}
        VERNAME=`cat ${VERS[$CHOICE]}`
    else
        echo " Please give an integer between 1 and $NUMBER"
    fi
    done

    echo " Are you sure you wish to uninstall the version for"
    yesno_default_yes "$VERNAME"

    if [[ $? == 1 ]]; then

        echo " Removing object files and libraries ... "
        \rm -f -r $SIFDECODE/objects/$VERSION
        echo " Removing module information files ... "
        \rm -f -r $SIFDECODE/modules/$VERSION
        echo " Removing environment information file ... "
        \rm -f -r $SIFDECODE/bin/sys/$VERSION
        echo " Removing make information file ... "
        \rm -f -r $SIFDECODE/makefiles/$VERSION
        echo " Removing version record file ... "
        \rm -f -r $SIFDECODE/versions/$VERSION
        success " Version for
  $VERNAME
 successfully removed."

    fi

    yesno_default_no 'Do you wish to uninstall another version'
    [[ $? == 0 ]] && finished='true'
done

