#!/bin/bash

#############
# FUNCTIONS #
#############
yesno () {
    case "$1" in
        Y|y)
            return 1
        ;;
        N|n)
            return 0
        ;;
        *)
            read -r -p "Invalid answer, please try again [Y/N] " YN
            yesno $YN
            return $?
        ;;
    esac
}

########
# MAIN #
########

echo "##########################"
echo "#  uCommand UPDATE tool  #"
echo "##########################"
echo ""
CWD=$(pwd)
DATE=$(date +"%d%m%Y-%H%M")
VERSION_FILE="VERSION.txt"
if [ -f "$VERSION_FILE" ]; then
    VER=$(cat VERSION.txt)
fi

REL=2.2.5
URL="https://mlsa2.swg.usma.ibm.com/workplace/dailybuilds/SFA"$REL

echo ""
echo "# Enter your IRIS username and password: "
echo ""
    read -r -p "  * Username: " USER
    read -r -s -p "  * Password: " PASSWORD
    
echo ""
echo ""
echo "# Retrieving version information"
BUILD=$(curl -k -s -u "iris\\$USER:$PASSWORD" $URL"/currentBuildLabel.txt")

# in case of auth failing, server response is a full html page with a message inside like "401 Authorization Required" 
if grep -q '401 Authorization Required' <<< $BUILD; then
	echo "Bad credentials, authentication is required"
	exit 1
fi

LATEST=$(curl -k -s -u "iris\\$USER:$PASSWORD" $URL"/"$BUILD"/setup/UCOMMAND_LATEST.txt")

echo "Current version: " $VER
echo "Latest version:  " $LATEST

echo ""
echo ""

if [ "$VER" != "$LATEST" ]; then
    echo "# There is a new version ("$LATEST") available."
    read -r -p "Do you want to download it? [Y/N] " DOWNLOAD
    yesno $DOWNLOAD
    if [ $? -eq 0 ]; then
        echo "Update cancelled by the user."
        exit 0
    fi
    
    # Avoid buffer issues
    sleep 1
    
    ##############
    # Run update #
    ##############
    
    echo ""
    echo "# Getting ready for backup"
    BACKUPS=$CWD"/ucommand_backups"
    if [ ! -d $BACKUPS ]; then
        mkdir -p $BACKUPS
    fi
    
    BACKUP=$BACKUPS"/ucommand-"$VER"_"$DATE
    TEMP=$CWD"/upgrade_temp"
    
    # Avoid buffer issues
    sleep 1
    
    echo ""
    echo "# Backing up the existing version in "
    echo "  "$BACKUP
    mkdir -p $BACKUP
    LS=$(ls)
    for FILE in $LS; do
        FILEPATH="$CWD/$FILE"
        if [ "$FILEPATH" != "$BACKUPS" ]; then
            echo "  -> "$FILEPATH
            cp -r "$FILEPATH" "$BACKUP/."
        fi
    done
    
    # Avoid buffer issues
    sleep 1
    
    echo ""
    echo "# Removing old version"
    for FILE in $LS; do
        FILEPATH="$CWD/$FILE"
        if [ "$FILEPATH" != "$BACKUPS" ] && [ "$FILE" != "update" ]; then
            rm -r "$FILEPATH"
        fi
    done
    
    # Avoid buffer issues
    sleep 1
    
    echo ""
    echo "# Retrieving last verision of the tool"
    UCOMMAND=$(curl -k -s -u "iris\\$USER:$PASSWORD" $URL"/"$BUILD"/setup" \
        | sed 's/<[^>]*>//g' \
        | grep socialcrm.ucd.cli \
        | sed 's/zip.*/zip/')
    echo "    "$UCOMMAND
    curl -k -u "iris\\"$USER:$PASSWORD $URL"/"$BUILD"/setup/"$UCOMMAND -o $UCOMMAND
    
    # Avoid buffer issues
    sleep 1
    
    echo ""
    echo "# Extracting the tool"
    unzip -q -o $UCOMMAND -d $TEMP
    
    LS=$(ls $TEMP/ucommand)
    for FILE in $LS; do
        if [ "$FILE" != "update" ]; then
            cp -r $TEMP/ucommand/$FILE $CWD
        else 
            cp -r $TEMP/ucommand/$FILE $CWD/update_new
        fi
        
    done
    
    # Avoid buffer issues
    sleep 1
    
    echo ""
    echo "# Removing temp files"
    rm -r $TEMP
    rm $UCOMMAND
    
    
    echo ""
    echo "# Restoring servers configurations"
    
    if [ -d $BACKUP/config/servers ]; then
    	if [ ! -d $CWD/config/servers ]; then
    		mkdir -p $CWD/config/servers
    	else
    		rm -r $CWD/config/servers/*
    	fi
        cp -r $BACKUP/config/servers/* $CWD/config/servers/
    fi
    
    echo ""
    echo ""
    echo "[SUCCESS] Upgrade completed"
    echo "Please, setup your new uCommand tool or copy config files from folder "
    echo "  "$BACKUP"/config "
    mv $CWD/update_new $CWD/update
else
    echo "Your uCommand is up to date"
    exit 0
fi