#!/bin/bash

print_usage()
{
    echo "Usage: install.sh x86 <path_to_x86_wine_libs>"
    echo "Usage: install.sh x64 <path_to_x86_64_wine_libs>"
    echo "           path_to_x86_wine_libs - is the path to the wine directory where x86 kernel32.dll.so is located" 
    echo "           path_to_x86_wine_libs - is the path to the wine directory where x86_64 kernel32.dll.so is located"
}

MACHINE_TYPE=$(uname -m)

# check args
if [ "$1" != "x86" ] &&  [ "$1" != "x64" ]; then
    print_usage
    exit
fi

if [ "$2" = "" ]
then
    print_usage
    exit
fi

if [ "$1" = "x64" ] && [ "$MACHINE_TYPE" != "x86_64" ]; then
    echo "FAILED. You can not install x86_64 library on x86 machine"
    exit
fi

# check wine is present
if ! command -v wine > /dev/null
then
    echo "Installation failed. Wine not found"
    exit
fi

# install grdwine.dll.so libs
if [ "$1" = "x86" ]
then
    echo "Try to install x86 grdwine.dll.so..."
    if file "$2/kernel32.dll.so" | grep "ELF 32-bit" > /dev/null
    then
        if cp -f "./x86/grdwine.dll.so" "$2/"
        then
            echo "SUCCESS"
        else
            echo  "Installation of x86 grdwine.dll.so failed. Could not copy ./x86/grdwine.dll.so to $2/"
        fi
    elif file "$2/kernel32.dll" | grep "80386" > /dev/null
    then
        if cp -f "./x86/grdwine.dll.so" "$2/"
        then
            echo "SUCCESS"
        else
            echo  "Installation of x86 grdwine.dll.so failed. Could not copy ./x86/grdwine.dll.so to $2/"
        fi
    else
        echo  "Installation of x86 grdwine.dll.so failed. $2 does not contains wine libs!"
    fi
fi

if [ "$1" = "x64" ] && [ "$MACHINE_TYPE" = "x86_64" ]
then
    echo "Try to install x86_64 grdwine.dll.so..."
    if file "$2/kernel32.dll.so" | grep "ELF 64-bit"  > /dev/null
    then
        if cp -f "./x86_64/grdwine.dll.so" "$2/"
        then
            echo "SUCCESS"
        else
            echo  "Installation of x86_64 grdwine.dll.so failed. Could not copy ./x86_64/grdwine.dll.so to $2/"
        fi
    elif file "$2/kernel32.dll" | grep "x86-64" > /dev/null
    then
        if cp -f "./x86_64/grdwine.dll.so" "$2/"
        then
            echo "SUCCESS"
        else
            echo  "Installation of x86_64 grdwine.dll.so failed. Could not copy ./x86_64/grdwine.dll.so to $2/"
        fi     
    else
        echo  "Installation of x86_64 grdwine.dll.so failed. $2 does not contains wine libs!"
    fi
fi
