#!/bin/bash
SOURCE_FOLDER='/opt/lsi/3rdpartylibs/x86_64'
FILENAME1='libsysfs.so'
FILENAME2='libsysfs.so.2'
FILENAME3='libsysfs.so.2.0.2'
DATE=$(date +%Y%m%d)
BACKUP_FOLDER="/tmp/$DATE"'_lsi_lib_backup'
CHANGE_MADE=0


if [[ ! -d $SOURCE_FOLDER ]]; then
    printf "Source directory %s appears to be missing. Please contact RSA support about obtaining lsi_libs_x86_64.tar.bz2 from KB #000032528. Exiting script.\n" "$SOURCE_FOLDER"
    exit 1
fi

if [[ ! -f $SOURCE_FOLDER/$FILENAME3 ]]; then
    printf "Library %s appears to be missing. Please contact RSA support about obtaining lsi_libs_x86_64.tar.bz2 from KB #000032528. Exiting script.\n" "$FILENAME3"
    exit 2
fi

# Bash file operators automatically dereference links except for -h and -L. Check if file exists and not symbolic link.
if [[ ! -e "$SOURCE_FOLDER/$FILENAME2" ]]; then
    ln -s $SOURCE_FOLDER/$FILENAME3 $SOURCE_FOLDER/$FILENAME2
    if [[ $? -eq 1 ]]; then
        printf "Failed in creating symbolic link. Exiting script.\n"
        exit 4
    else
        printf "Created symbolic link %s to point to %s\n" "$SOURCE_FOLDER/$FILENAME2" "$SOURCE_FOLDER/$FILENAME3"
    fi
    CHANGE_MADE=1
elif [[ ! -L "$SOURCE_FOLDER/$FILENAME2" ]]; then
    printf "===> %s exists and is not a symlink, backing up original file to %s and creating a symlink\n" "$FILENAME2" "$BACKUP_FOLDER"
    create_backup_dir
    mv $SOURCE_FOLDER/$FILENAME2 "$BACKUP_FOLDER"
    sleep 4
    ln -s $SOURCE_FOLDER/$FILENAME3 $SOURCE_FOLDER/$FILENAME2
    if [[ $? -eq 1 ]]; then
        printf "Failed in creating symbolic link. Exiting script.\n"
        exit 5
    else
        printf "Created symbolic link %s to point to %s\n" "$SOURCE_FOLDER/$FILENAME2" "$SOURCE_FOLDER/$FILENAME3"
    fi
    CHANGE_MADE=1
fi


if [[ ! -e "$SOURCE_FOLDER/$FILENAME1" ]]; then
    ln -s $SOURCE_FOLDER/$FILENAME2 $SOURCE_FOLDER/$FILENAME1
    if [[ $? -eq 1 ]]; then
        printf "Failed in creating symbolic link. Exiting script.\n"
        exit 6
    else
        printf "Created symbolic link %s to point to %s\n" "$SOURCE_FOLDER/$FILENAME1" "$SOURCE_FOLDER/$FILENAME2"
    fi
    CHANGE_MADE=1
elif [[ ! -L "$SOURCE_FOLDER/$FILENAME1" ]]; then
    printf "===> %s exists and is not a symlink, backing up original file to %s and creating a symlink\n" "$FILENAME1" "$BACKUP_FOLDER"
    create_backup_dir
    mv $SOURCE_FOLDER/$FILENAME1 "$BACKUP_FOLDER"
    sleep 4
    ln -s $SOURCE_FOLDER/$FILENAME2 $SOURCE_FOLDER/$FILENAME1
    if [[ $? -eq 1 ]]; then
        printf "Failed in creating symbolic link. Exiting script.\n"
        exit 7
    else
        printf "Created symbolic link %s to point to %s\n" "$SOURCE_FOLDER/$FILENAME1" "$SOURCE_FOLDER/$FILENAME2"
    fi
    CHANGE_MADE=1
fi

if [[ $CHANGE_MADE -eq 0 ]]; then
    printf "Your files looks OK ....... no further actions required Thank you!\n"
fi


