#!/bin/bash

set -e  # Exit on errors

# Variables
PACKAGE_NAME="IDriveForLinux"
NEW_VERSION="1.8.0"
VERSION_FILE_PATH="/opt/IDriveForLinux/idriveIt/cache/version"
REQUIRED_VERSION_SCRIPTS="3.0.0"
APP_VERSION_FILE_PATH="/opt/IDriveForLinux/AppVersion"

# Function to compare two version strings

check_os_version() {
    # Get the OS name and version
     if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
        VERSION=$VERSION_ID
    else
        return
    fi

    case $OS in
        ubuntu)
            REQUIRED_VERSION=19
            ;;
        linuxmint)
            REQUIRED_VERSION=20
            ;;
        centos)
            REQUIRED_VERSION=8
            ;;
        fedora)
            REQUIRED_VERSION=33
            ;;
        debian)
            REQUIRED_VERSION=10
            ;;
        *)
            echo "" 
            echo ""
            echo "Your machine '$OS $VERSION' is not under supported list of 'IDrive Linux Desktop' application. Refer 'System Requirements' section from the link below. If you face any issues after installation please contact support" 
            echo ""
            echo "Link: https://www.idrive.com/online-backup-download"
            echo ""
            ;;
    esac

    # Compare versions
    if [ "$(echo "$VERSION < $REQUIRED_VERSION" | bc -l)" -eq 1 ]; then
        echo "" 
        echo "********************************************************************************"
        echo ""
        echo "Your machine '$OS $VERSION' is not supported for 'IDrive Linux Desktop' application. Download 'IDrive Linux Command Line' package from the link below"
        echo ""
        echo "Link: https://www.idrive.com/linux-remote-manage"
        echo ""
        echo "********************************************************************************"
        echo ""
        exit 1
    fi
}

# Function to compare two version strings
version_less_than() {
    local current_version="$1"
    local required_version="$2"

    # Compare versions using `sort -V`
    [ "$(printf '%s\n%s' "$current_version" "$required_version" | sort -V | head -n1)" = "$current_version" ] &&
    [ "$current_version" != "$required_version" ]
}

# Function to check the version in the version file
check_version_file() {
    # Check if AppVersion file exists
    if [ -f "$APP_VERSION_FILE_PATH" ]; then
        return 0  # AppVersion file found, no error
    fi

    # If AppVersion is not found, check for Version file
    if [ ! -f "$VERSION_FILE_PATH" ]; then
        return 0  # Continue script execution if no Version file is found
    fi

    CURRENT_VERSION=$(cat "$VERSION_FILE_PATH" 2>/dev/null | tr -d '[:space:]')
    if [ -z "$CURRENT_VERSION" ]; then
        return 0  # Continue if Version file is empty
    fi

    if version_less_than "$CURRENT_VERSION" "$REQUIRED_VERSION_SCRIPTS"; then
        echo "" 
        echo "********************************************************************************"
        echo ""
        echo "'Your IDrive scripts version is outdated. Run \"check_for_update.pl\" to update to the latest version and then proceed with the installation.'"
        echo ""
        echo "********************************************************************************"
        echo ""
        exit 1
    fi
}

# Function to get the installed version of the package
get_installed_version() {
    dpkg=$(command -v dpkg-query || echo '')
    rpm=$(command -v rpm || echo '')

    if [ -n "$dpkg" ]; then
        dpkg-query -W -f='${Version}' "$PACKAGE_NAME" 2>/dev/null || echo "none"
	elif [ -n "$rpm" ]; then
        rpm -q --qf "%{VERSION}\n" "$PACKAGE_NAME" 2>/dev/null || echo "none"
    fi
}

# Function to check for IDrive 360 application and show uninstall message
check_idrive360() {
    if [ -d "/opt/IDrive360/resources/" ]; then
        echo ""
        echo "********************************************************************************"
        echo ""
        echo "**Kindly uninstall IDrive 360 application before installing IDrive native application**"
        echo ""
        
        # Detect OS type and show appropriate uninstall command
        if command -v apt >/dev/null 2>&1; then
            echo "**Use the following command to uninstall:**"
            echo "sudo apt remove idrive360-client"
        elif command -v yum >/dev/null 2>&1; then
            echo "**Use the following command to uninstall:**"
            echo "sudo yum remove idrive360-client"
        elif command -v dnf >/dev/null 2>&1; then
            echo "**Use the following command to uninstall:**"
            echo "sudo dnf remove idrive360-client"
        else
            echo "**Please uninstall IDrive360 native application manually**"
        fi
        
        echo ""
        echo "********************************************************************************"
        echo ""
        exit 1
    fi
}


# Main logic
main() {
    env > /tmp/idrive.user.perm.log
    check_os_version
    check_idrive360
    check_version_file
    INSTALLED_VERSION=$(get_installed_version)

    if [ "$INSTALLED_VERSION" != "none" ]; then
        echo "$PACKAGE_NAME is installed. Installed version: $INSTALLED_VERSION"

        if [ "$INSTALLED_VERSION" = "$NEW_VERSION" ]; then
            echo "The installed version is already up-to-date ($NEW_VERSION). No update required."
            exit 0
        else
            echo "Updating $PACKAGE_NAME to version $NEW_VERSION..."
            # Perform update logic here
            exit 0
        fi
    else
        echo "$PACKAGE_NAME is not installed. Proceeding with installation..."
        # Perform installation logic here
        exit 0
    fi
}

# Run the main function
main
