#!/bin/bash

# Version: 1.0.0
# Date: 2023-10-12
# Authors: Christian Muck, Patrik Burzynski, Wilfrid Utz
# Installation scripts: MIT License, (C) Copyright 2023 OMiLAB

# Check if Wine is installed. If it is not installed or the --forceop
# argument is specified, then it tries to install Wine.

# This script uses set_variables.sh to set various variables that are used.
# The relevant variables are:
# force_operation - Performs the operation independent of checks / user inputs.
# linux_package_manager - The package manager available on the system.

# Notes about some specifics of the script/s:
# * ${@} - represents all the parameters / arguments that have been passed to
#   this script.
# * Calling a script via "./filename.sh" executes them in a separate process
#   (at least in zsh), so they should have their own local (environment)
#   variables.
# * Adding a script via the source commands behaves as if the code from the
#   other script was part of this script, similar to #include in C/C++.



# The following establishes the absolute path to this scripts directory.
ABSOLUTE_SCRIPT_DIRECTORY="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")"&>/dev/null && pwd)"
# Process passed arguments and load various relevant variables and functions.
source "${ABSOLUTE_SCRIPT_DIRECTORY}/common_script.sh"



# Check if Wine is installed. The wine64 command is more important to us, as the scripts use it.
command -v wine64 &>/dev/null
wine64_command_available=$?
command -v wine &>/dev/null
wine_command_available=$?
# Some wine versions don't have the wine64 command anymore.
# We stick with wine64 so that these scripts (and the ModTk/DevTk) still work with Wine versions that use wine64.
# So we create a wine64 symbolic link to the wine file, assuming that wine supports 64-bit.
# IMPORTANT: this code is also repeated further below as part of installing wine.
if [ ${wine64_command_available} -ne 0 ] && [ $wine_command_available -eq 0 ]
then
    echo "Adding link $(which wine)64 pointing to $(which wine) (to support different Wine versions)."
    sudo ln -s "$(which wine)" "$(which wine)64"
    # Repeating check to update variable.
    command -v wine64 &>/dev/null
    wine64_command_available=$?
fi
if [ ${wine64_command_available} -eq 0 ]
then
    echo "$(wine64 --version) already installed."
else
    echo "Wine not installed."
fi



# Install Wine.
if [ ${wine64_command_available} -ne 0 ] || [ ${force_operation} -eq 0 ]
then
    if [ -z "${linux_package_manager}" ]
    then
        echo ${error_style}"Package manager could not be determined."${default_style}
    else
        # Installation of wine is now a bit more complicated, as it requires downloading winehq-staging.
        # For this we have to determine what OS and version the user is using, as different commands are necessary to add the winehq repository.
        linux_distribution=$(cat /etc/os-release | grep ^ID= | cut -d '=' -f 2-)
        linux_version=$(cat /etc/os-release | grep ^VERSION_ID= | cut -d '=' -f 2-)
        linux_version="${linux_version//\"/}" # Remove the double quotes.
        setup_winehq_repository=1
        echo "Linux version: ${linux_distribution} ${linux_version}"
        if [ "${linux_distribution}" = "ubuntu" ]
        then
            echo "Setting up WineHQ repository for Ubuntu"
            sudo dpkg --add-architecture i386
            sudo mkdir -pm755 /etc/apt/keyrings
            # Update the key from winehq.
            wget -O - https://dl.winehq.org/wine-builds/winehq.key | sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/winehq-archive.key -
            # The .sources always get downloaded again in case there might have been changes.
            if [ "${linux_version}" = "24.10" ]
            then
                sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/oracular/winehq-oracular.sources
                setup_winehq_repository=0
            elif [ "${linux_version}" = "24.04" ]
            then
                sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/noble/winehq-noble.sources
                setup_winehq_repository=0
            elif [ "${linux_version}" = "22.04" ]
            then
                sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/jammy/winehq-jammy.sources
                setup_winehq_repository=0
            elif [ "${linux_version}" = "20.04" ]
            then
                sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/focal/winehq-focal.sources
                setup_winehq_repository=0
            fi
        fi
        if [ "${linux_distribution}" = "debian" ]
        then
            echo "Setting up WineHQ repository for Debian"
            sudo dpkg --add-architecture i386
            sudo mkdir -pm755 /etc/apt/keyrings
            # Update the key from winehq.
            wget -O - https://dl.winehq.org/wine-builds/winehq.key | sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/winehq-archive.key -
            # The .sources always get downloaded again in case there might have been changes.
            if [ "${linux_version}" = "12" ]
            then
                sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/debian/dists/bookworm/winehq-bookworm.sources
                setup_winehq_repository=0
            elif [ "${linux_version}" = "11" ]
            then
                sudo wget -NP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/debian/dists/bullseye/winehq-bullseye.sources
                setup_winehq_repository=0
            fi
        fi

        # When the WineHQ repository has been set up, then we can install wine.
        if [ $setup_winehq_repository -eq 0 ]
        then
            echo "Installing Wine"
            # Using apt update to get the latest packages.
            sudo apt update
            # This used to work, but then after some wine updates the wine and winehq-stable branches caused a crash when trying to start DevTk / ModTk.
            #sudo ${linux_package_manager} install wine
            # Currently wine-10.3 (Staging) doesn't cause the crash ad startup and
            # also doesn't have the issue where some libraries crash when creating connectors.
            # At time of writing it seemed that wine-10 is available for all of the set up linux distributions / versions.
            sudo ${linux_package_manager} install winehq-staging

            # Some wine versions don't have the wine64 command anymore.
            # We stick with wine64 so that these scripts (and the ModTk/DevTk) still work with Wine versions that use wine64.
            # So we create a wine64 symbolic link to the wine file, assuming that wine supports 64-bit.
            # IMPORTANT: this code is also repeated further up BEFORE installing wine.
            command -v wine64 &>/dev/null
            wine64_command_available=$?
            command -v wine &>/dev/null
            wine_command_available=$?
            if [ ${wine64_command_available} -ne 0 ] && [ $wine_command_available -eq 0 ]
            then
                echo "Adding link $(which wine)64 pointing to $(which wine) (to support different Wine versions)."
                sudo ln -s "$(which wine)" "$(which wine)64"
            fi
        else
            # Otherwise we ask the user to manually install wine.
            #TODO send the user to WineHQ to manually install wine.
            echo ${warning_style}"This script can not automatically install wine on this system."
            echo "Please install the latest Wine Staging version manually (versions 9.9 to 9.18 or 10.x)"
            echo "You can find details at https://gitlab.winehq.org/wine/wine/-/wikis/Download"${default_style}
        fi
    fi
fi



# Check if Wine is installed and "return" 0 (true) or 1 (false).
command -v wine64 &>/dev/null
wine64_command_available=$?
if [ ${wine64_command_available} -ne 0 ]
then
    echo ${error_style}"FAILED installing Wine."
    echo "Please install Wine manually."${default_style}
    echo "You can find details at https://gitlab.winehq.org/wine/wine/-/wikis/Download"
    exit 1
else
    exit 0
fi
