#!/bin/bash

DIRECTORY="$(dirname "$(dirname "$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )")")"

function error {
  echo -e "\\e[91m$1\\e[39m"
  exit 1
}


hardware="$(cat /proc/cpuinfo)"
if [ ! -z "$(echo "$hardware" | grep ARMv7)" ];then
  hardware='pi3'
elif [ ! -z "$(echo "$hardware" | grep ARMv6)" ];then
  hardware='pi0'
else
  hardware='pi4'
fi

if [ "$hardware" == 'pi0' ];then
  error "Wine is not compatible with the Raspberry Pi Zero or other ARMv6 boards."
fi

if [ ! -e /proc/config.gz ];then
  sudo modprobe configs || error "Failed to run sudo modprobe configs!"
  if [ ! -e /proc/config.gz ];then
    error "/proc/config.gz does not exist after running sudo modprobe configs!"
  fi
fi

vmsplit_output="$(gunzip < /proc/config.gz | grep VMSPLIT)"
if [ -z "$vmsplit_output" ];then
  kernel="$(uname -m)"
  if [ $kernel == aarch64 ];then
    echo "No memory split information due to running a 64-bit kernel. Continuing..."
  else
    echo "No memory split information and not running a 64-bit kernel. Strange."
    sleep 2
    echo "Continuing..."
  fi
elif echo "$vmsplit_output" | grep -q "^CONFIG_VMSPLIT_2G=y" || echo "$vmsplit_output" | grep -q "^# CONFIG_VMSPLIT_3G is not set" ;then
  
  #ensure hardware is pi3 for kernel compiling to work
  if [ "$hardware" != 'pi3' ];then
    error "This script is not capable of handling your $hardware board with a 2G/2G memory split.\nWhatever you did to get yourself into this situation, undo it and try installing Wine again."
  fi
  
  #continue asking until valid answer
  while true;do
    echo -e "You are using a kernel with a 2G/2G memory split.\nWine will not work on such systems. What would you like to do?
1. Switch to the 64-bit kernel (about 2 minutes)
2. Compile a 3G/1G kernel (several hours)
3. Install a precompiled 3G/1G kernel (about 2 minutes but might be outdated)
4. Exit"
    read -n1 answer
    echo ''
    if [ "$answer" == 1 ];then
      #switch to 64bit kernel
      
      echo "arm_64bit=1" | sudo tee --append /boot/config.txt >/dev/null
      echo -e "The 64-bit kernel has been enabled by adding 'arm_64bit=1' to /boot/config.txt\nPlease reboot and install the Wine app again."
      sleep infinity
    elif [ "$answer" == 2 ];then
      #compile 3g/1g kernel
      
      #backup ~/linux if it exists
      rm -rf ~/linux.bak
      [ -e ~/linux ] && (echo "$HOME/linux already exists, moving it to $HOME/linux.bak" ; mv -f ~/linux ~/linux.bak)
      
      #download kernel source code
      git clone --depth=1 https://github.com/raspberrypi/linux || error "Failed to git clone the raspberry pi kernel repo!"
      
      #build for pi3
      cd linux
      KERNEL=kernel7
      make -j8 bcm2709_defconfig
      
      #change memory split config
      echo "Setting memory split to 3G/1G"
      sed -i 's/CONFIG_VMSPLIT_2G=y/# CONFIG_VMSPLIT_2G is not set/g' ~/linux/.config || error "sed failed to edit $HOME/linux/.config file!"
      sed -i 's/# CONFIG_VMSPLIT_3G is not set/CONFIG_VMSPLIT_3G=1/g' ~/linux/.config
      
      echo '' | make -j8 zImage modules dtbs || error "Failed to make bcm2709_defconfig zImage modules dtbs!"
      
      #install
      sudo make modules_install || error "sudo make modules_install failed!"
      sudo cp arch/arm/boot/dts/*.dtb /boot/ || error "Failed to copy dtb files to /boot!"
      sudo cp arch/arm/boot/dts/overlays/*.dtb* /boot/overlays/ || error "Failed to copy overlays to /boot/overlays!"
      sudo cp arch/arm/boot/dts/overlays/README /boot/overlays/
      sudo cp arch/arm/boot/zImage /boot/$KERNEL.img || error "Failed to copy kernel to /boot/$KERNEL.img!"
      cd
      rm -rf ~/linux
      
      #message
      echo -e "It appears the 3G/1G kernel has been built and installed successfully.\nPlease reboot and install the Wine app again."
      sleep infinity
    elif [ "$answer" == 3 ];then 
      #install precompiled 3g/1g kernel
      
      #backup ~/linux if it exists
      rm -rf ~/linux.bak
      [ -e ~/linux ] && (echo "$HOME/linux already exists, moving it to $HOME/linux.bak" ; mv -f ~/linux ~/linux.bak)
      #download precompiled kernel
      echo "Downloading precompiled kernel..."
      wget https://github.com/Itai-Nelken/RPi-3g-1g-kernel-wine/releases/download/3/rpi23_3g1g_kernel.tar.xz -O ~/3g1g-rpi-kernel.tar.xz || error "Failed to download prebuilt kernel!"
      #extract precompiled kernel
      echo "Extracting prebuilt kernel..."
      tar -xf ~/3g1g-rpi-kernel.tar.xz || error "Failed to extract kernel!"
      cd linux || error "Failed to change folder to ~/linux!"
      #install the precompiled kernel
      export KERNEL=kernel7
      sudo make modules_install || error "sudo make modules_install failed!"
      sudo cp arch/arm/boot/dts/*.dtb /boot/ || error "Failed to copy dtb files to /boot!"
      sudo cp arch/arm/boot/dts/overlays/*.dtb* /boot/overlays/ || error "Failed to copy overlays to /boot/overlays!"
      sudo cp arch/arm/boot/dts/overlays/README /boot/overlays/
      sudo cp arch/arm/boot/zImage /boot/$KERNEL.img || error "Failed to copy kernel to /boot/$KERNEL.img!"
      cd
      rm -rf linux
      #message
      echo -e "It appears the precompiled 3G/1G kernel has been installed successfully.\nPlease reboot and install the Wine app again."
      sleep infinity
    elif [ "$answer" == 4 ];then
      exit 1
    else
      echo "Invalid response. Must be '1', '2', '3' or '4'."
    fi
  done
else
  echo "Your system is using a 3G/1G kernel. Continuing..."
fi

#Past this point, the pi is running a Wine-compatible kernel.

#install box86
if ! command -v box86 || [ "$(cat "${DIRECTORY}/data/status/Box86" 2>/dev/null)" != 'installed' ];then
  echo 'Installing box86...'
  "${DIRECTORY}/manage" install Box86 || error "Box86 failed to install somehow!"
  if ! command -v box86 ;then
    error "Box86 executable does not exist!"
  else
    echo "installed" > "${DIRECTORY}/data/status/Box86"
  fi
fi

pkill -9 wine
sudo apt purge -y wine &>/dev/null &

# Remove old wine, while leaving config intact
sudo rm -rf /usr/local/bin/wine /usr/local/bin/wineboot /usr/local/bin/wineserver /usr/local/bin/winecfg /usr/local/bin/winetricks ~/wine.tgz ~/wine ~/.cache/winetricks ~/.cache/wine 2>/dev/null

# Get dependencies
"${DIRECTORY}/pkg-install" "cabextract" "$(dirname "$0")" || exit 1

# Download
wget https://twisteros.com/wine.tgz -O ~/wine.tgz || error 'Failed to download wine!'
tar zxf ~/wine.tgz || error 'Failed to extract wine!'
rm ~/wine.tgz

# Install
#sudo ln -s ~/wine/bin/wine /usr/local/bin/wine
sudo ln -s ~/wine/bin/winecfg /usr/local/bin/winecfg
sudo ln -s ~/wine/bin/wineserver /usr/local/bin/wineserver
sudo ln -s ~/wine/bin/wineboot /usr/local/bin/wineboot

echo "#!/bin/bash
setarch linux32 -L $HOME/wine/bin/wine"' "$@"' | sudo tee /usr/local/bin/wine >/dev/null
sudo chmod +x /usr/local/bin/wine /usr/local/bin/wineboot /usr/local/bin/wineserver /usr/local/bin/winecfg

#winetricks pre-patched
#see https://discord.com/channels/670543161525010442/736736690932285481/793931182302560277
#sudo wget https://cdn.discordapp.com/attachments/736736690932285481/793931182249213972/winetricks -O /usr/local/bin/winetricks || error "Failed to get winetricks!"
#winetricks patch (doesn't work)
#sudo sed -i 's|echo "${arg%%=*}"=\""${arg#*=}"\"|echo ${arg%%=*}=\"${arg#*=}\"|g' /usr/local/bin/winetricks

sudo wget https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks -O /usr/local/bin/winetricks || error "Failed to download winetricks!"
sudo chmod +x /usr/local/bin/winetricks


#create menu button to winecfg
echo "[Desktop Entry]
StartupNotify=true
Terminal=false
Type=Application
Name=Wine configuration
Exec=wine winecfg
Icon=$(dirname "$0")/icon-64.png
Categories=System;
Comment=Configure wine" > ~/.local/share/applications/wine-config.desktop

echo "[Desktop Entry]
Name=Winetricks
Comment=Work around problems and install applications under Wine
Exec=bash -c 'BOX86_NOBANNER=1 box86 winetricks --gui'
Terminal=false
Icon=$(dirname "$0")/icon-64.png
Type=Application
Categories=System;" > ~/.local/share/applications/winetricks.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Desktop
Comment=Graphical desktop for Wine
Icon=$(dirname "$0")/icon-64.png
Exec=/usr/local/bin/wine explorer /desktop=shell,1280x720 explorer.exe
Terminal=false
Categories=System;" > ~/.local/share/applications/wine-explorer.desktop


# Boot wine (make fresh wineprefix in ~/.wine
BOX86_NOBANNER=1
setarch linux32 -L box86 ~/wine/bin/wine wineboot

#wait until above process exits
while [ ! -z "$(ps aux | grep -i 'wine C:' | grep -v grep)" ];do
  sleep 1
done
echo "First wineboot finished. Now updating wine prefix..."

#update the wine prefix (~/.wine) to fix the issue that causes wine to not know its system drive
#running as background process - terminal will exit but that's ok
setsid wine wineboot -u

exit 0
