#!/bin/bash

#note to maintainer, if you change the below version make sure to update it in the uninstall script as well
version=8.14

#install box64
"${DIRECTORY}/manage" install-if-not-installed Box64 || error "Box64 failed to install somehow!"
if ! command -v box64 >/dev/null ;then
  error "User error: Pi-Apps thinks Box64 is installed, however no command named 'box64' exists. Please install Box64 manually."
fi
#upgrade box86
echo "Upgrading Box64 if necessary:"
apt_update
apt_lock_wait
sudo apt install --only-upgrade box64-* -y
echo "Installed Box64 version:"
box64 -v || error "User error: Something went wrong when trying to run Box64."

# Remove old wine, while leaving config intact
pkill -9 wine
command -v wineserver >/dev/null && wineserver -k
command -v wine >/dev/null && sudo apt purge -y wine &>/dev/null &
sudo rm -rf /usr/local/bin/wine /usr/local/bin/wineboot /usr/local/bin/wineserver /usr/local/bin/winecfg /usr/local/bin/winetricks /opt/wine-${version} ~/.cache/winetricks ~/.cache/wine 2>/dev/null

# Get dependencies
install_packages cabextract p7zip-full || exit 1

# Download wine to /opt
wget https://github.com/Pi-Apps-Coders/files/releases/download/large-files/wine-${version}.tar.gz -O /tmp/wine-${version}.tar.gz || error 'Failed to download wine!'
sudo tar -xvf /tmp/wine-${version}.tar.gz -C /opt || error 'Failed to extract wine!'
rm -f /tmp/wine-${version}.tar.gz

#edit wine.inf to disable mime-associations. Nobody wants to double-click a text file, wonder why nothing is happening, then watch 15 Wine notepad windows pop up. Ask me how I know.
sudo sed -i 's/winemenubuilder.exe -a -r/winemenubuilder.exe -r/' /opt/wine-${version}/share/wine/wine.inf #See: https://askubuntu.com/a/400430

#download winetricks
wget -O /tmp/winetricks "https://raw.githubusercontent.com/theofficialgman/winetricks/master/src/winetricks" || exit 1
sudo mv /tmp/winetricks /opt/wine-${version}/bin/winetricks || error "Failed to move winetricks script to /opt/wine-${version}/bin folder!"
sudo chmod +x /opt/wine-${version}/bin/winetricks

#download Mono to universal location (to be installed automatically in all wine prefixes)
#according to https://wiki.winehq.org/Mono#Versions, use Mono 8.0.0 for Wine 8.11
#wine mono pacakge is called -x86 but contains both x86 and x86_64 binaries
sudo mkdir -p /opt/wine-${version}/share/wine/mono
wget -O "/tmp/wine-mono-8.0.0-x86.tar.xz" 'https://dl.winehq.org/wine/wine-mono/8.0.0/wine-mono-8.0.0-x86.tar.xz' || exit 1
sudo tar -xvf "/tmp/wine-mono-8.0.0-x86.tar.xz" -C "/opt/wine-${version}/share/wine/mono" || exit 1
rm -f "/tmp/wine-mono-8.0.0-x86.tar.xz"

#download Gecko to universal location (to be installed automatically in all wine prefixes)
#according to https://wiki.winehq.org/Gecko, use Gecko 2.47.4 for Wine 8.11
sudo mkdir -p /opt/wine-${version}/share/wine/gecko
wget -O "/tmp/wine-gecko-2.47.4-x86_64.tar.xz" 'https://dl.winehq.org/wine/wine-gecko/2.47.4/wine-gecko-2.47.4-x86_64.tar.xz' || exit 1
sudo tar -xvf "/tmp/wine-gecko-2.47.4-x86_64.tar.xz"  -C "/opt/wine-${version}/share/wine/gecko" || exit 1
rm -f "/tmp/wine-gecko-2.47.4-x86_64.tar.xz"

status "Creating terminal commands:"
echo "  - winecfg"
sudo ln -s /opt/wine-${version}/bin/winecfg /usr/local/bin/winecfg
echo "  - wineserver"
sudo ln -s /opt/wine-${version}/bin/wineserver /usr/local/bin/wineserver
echo "  - wineboot"
sudo ln -s /opt/wine-${version}/bin/wineboot /usr/local/bin/wineboot
echo "  - wine"
sudo ln -s /opt/wine-${version}/bin/wine /usr/local/bin/wine

echo "  - winetricks"
echo "#!/bin/bash
BOX64_NOBANNER=1 /opt/wine-${version}/bin/winetricks"' "$@"' | sudo tee /usr/local/bin/winetricks >/dev/null

#make them all executable
status -n "Making executable... "
sudo chmod +x /usr/local/bin/winecfg /usr/local/bin/wineserver /usr/local/bin/wineboot /usr/local/bin/wine /usr/local/bin/winetricks || error "\nFailed to mark all commands as executable. Most likely one failed to be generated or copied. These files are:\n/usr/local/bin/winecfg\n/usr/local/bin/wineserver\n/usr/local/bin/wineboot\n/usr/local/bin/wine"
status_green "Done"

#get icons from wine-stuff repo
cd /tmp
rm -rf wine-stuff
git clone https://github.com/Botspot/wine-stuff || error "Failed to clone wine-stuff repository!"
sudo mv wine-stuff/icons /opt/wine-${version}
sudo mv wine-stuff/Windows_10.msstyles /opt/wine-${version}
sudo chown -R root:root  /opt/wine-${version}/icons /opt/wine-${version}/Windows_10.msstyles
rm -rf wine-stuff

#create menu launchers
status -n "Creating Menu launchers... "

#Remove wine auto-generated desktop files that handle mimetypes. Nobody in their right mind would want this.
#See: https://askubuntu.com/a/400430
rm -f ~/.local/share/mime/packages/x-wine*
rm -f ~/.local/share/applications/wine-extension*
rm -f ~/.local/share/icons/hicolor/*/*/application-x-wine-extension*
rm -f ~/.local/share/mime/application/x-wine-extension*

echo "[Desktop Entry]
StartupNotify=true
Terminal=false
Type=Application
Name=Wine Configuration
Exec=wine winecfg
Icon=/opt/wine-${version}/icons/winecfg.png
Categories=System;
Comment=Configure wine" | sudo tee /usr/share/applications/wine-config.desktop

echo "[Desktop Entry]
Name=Winetricks
Comment=Work around problems and install applications under Wine
Exec=bash -c 'BOX64_NOBANNER=1 box64 winetricks --gui'
Terminal=false
Icon=/opt/wine-${version}/icons/winetricks.png
Type=Application
Categories=System;" | sudo tee /usr/share/applications/wine-tricks.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Desktop
Comment=Wine graphical desktop environment to mimic a Windows OS
Icon=/opt/wine-${version}/icons/wine-desktop.png
Exec=wine explorer /desktop=shell,1280x720
Terminal=false
Categories=System;" | sudo tee /usr/share/applications/wine-explorer.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Program Manager
Comment=Install/Remove Windows programs
Icon=/opt/wine-${version}/icons/wine-program-manager.png
Exec=wine uninstaller
Terminal=false
Categories=System;" | sudo tee /usr/share/applications/wine-uninstaller.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Task Manager
Comment=View running processes within Wine
Icon=/opt/wine-${version}/icons/winetask.png
Exec=wine taskmgr
Terminal=false
Categories=System;" | sudo tee /usr/share/applications/wine-taskmgr.desktop

echo "[Desktop Entry]
StartupNotify=false
Version=1.0
Type=Application
Name=Wine Killer
Comment=Terminate any running Wine processes
Icon=/opt/wine-${version}/icons/winestop.png
Exec=wineserver -k
Terminal=false
Categories=System;" | sudo tee /usr/share/applications/wine-killer.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Reset
Comment=Clean out the default Wine prefix and start over
Icon=/opt/wine-${version}/icons/wine-regenerate.png
Exec=bash -c "\""yad --window-icon=/opt/wine-${version}/icons/wine-regenerate.png --title='Wine Reset' --text='Are you sure you want to DELETE all data and applications in your Wine prefix and start over?' --center --button=Cancel:1 --button=Yes:0 --on-top && ${DIRECTORY}/etc/terminal-run 'echo y | winetricks annihilate -q ; generate-wine-prefix' 'Generating Wine prefix...'"\""
Terminal=false
Categories=System;" | sudo tee /usr/share/applications/wine-regenerate.desktop
status_green "Done"

cat << EOF | sudo tee /usr/local/bin/generate-wine-prefix >/dev/null
#!/bin/bash
echo

#set up functions
$(declare -f error)
$(declare -f status)
$(declare -f warning)

if [ "\$(id -u)" == 0 ];then
  error "Please don't run this script with sudo."
fi

if [ -z "\$WINEPREFIX" ];then
  WINEPREFIX="\$HOME/.wine"
fi
export WINEPREFIX
export BOX64_NOBANNER=1 #hide box64 output (for cosmetics)

if [ -e "\$HOME/.wine" ];then
  status "Checking Wine prefix at \$WINEPREFIX..."
  echo "To choose another prefix, set the WINEPREFIX variable."
  echo "Waiting 5 seconds..."
  sleep 5
  # check for existance of incompatible prefix (see server_init_process https://github.com/wine-mirror/wine/blob/884cff821481b4819f9bdba455217bd5a3f97744/dlls/ntdll/unix/server.c#L1544-L1670)
  # Boot wine and check for errors (make fresh wineprefix)
  output="\$(set -o pipefail; wine wineboot 2>&1 | tee /dev/stderr; )" #this won't display any dialog boxes that require a button to be clicked
  if [ "\$?" != 0 ]; then
    warning "Your previously existing Wine prefix failed with an error (see above). It has been removed and will be re-generated."
    rm -rf "\$HOME/.wine"
    wine wineboot #this won't display any dialog boxes that require a button to be clicked
  fi
  #wait until above process exits
  sleep 2
  while [ ! -z "\$(pgrep -i 'wine C:')" ];do
    sleep 1
  done
else
  status "Generating Wine prefix at \$WINEPREFIX..."
  echo "To choose another prefix, set the WINEPREFIX variable."
  echo "Waiting 5 seconds..."
  sleep 5
  # Boot wine (make fresh wineprefix)
  wine wineboot #this won't display any dialog boxes that require a button to be clicked
  #wait until above process exits
  sleep 2
  while [ ! -z "\$(pgrep -i 'wine C:')" ];do
    sleep 1
  done
fi

status "Making registry changes..."
TMPFILE="\$(mktemp)" || exit 1
echo 'REGEDIT4' > \$TMPFILE

#enable font smoothing - see https://askubuntu.com/a/219795
echo "  - Font smoothing"

MODE=2 # 0 = disabled; 2 = enabled
TYPE=2 # 1 = regular;  2 = subpixel
ORIENTATION=1 # 0 = BGR; 1 = RGB

echo '
[HKEY_CURRENT_USER\Control Panel\Desktop]
"FontSmoothing"="'\$MODE'"
"FontSmoothingOrientation"=dword:0000000'\$ORIENTATION'
"FontSmoothingType"=dword:0000000'\$TYPE'
"FontSmoothingGamma"=dword:00000578' >> \$TMPFILE

echo "  - Windows 10 appearance theme"
mkdir -p "\$WINEPREFIX/drive_c/windows/Resources/Themes/Windows_10"
cp -f /opt/wine-${version}/Windows_10.msstyles "\$WINEPREFIX/drive_c/windows/Resources/Themes/Windows_10"

echo '
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager]
"ColorName"="NormalColor"
"DllName"="C:\\\\windows\\\\Resources\\\\Themes\\\\Windows_10\\\\Windows_10.msstyles"
"FlatMenu"=dword:00000000
"GradientCaption"=dword:00000001
"IconTitleFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,\
  00,00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"NonClientMetrics"=hex:f8,01,00,00,01,00,00,00,10,00,00,00,10,00,00,00,12,00,\
  00,00,12,00,00,00,f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,\
  00,00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,0f,00,\
  00,00,0f,00,00,00,fa,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,\
  00,00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,12,00,\
  00,00,12,00,00,00,f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,\
  00,00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,f5,ff,\
  ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,00,00,00,00,00,00,\
  22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,f5,ff,ff,ff,00,00,00,00,00,00,\
  00,00,00,00,00,00,90,01,00,00,00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,\
  00,6d,00,61,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00
"SizeName"="NormalSize"
"ThemeActive"="1"

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager\Control Panel\Colors]
"ActiveBorder"="212 208 200"
"ActiveTitle"="10 36 106"
"AppWorkSpace"="128 128 128"
"Background"="58 110 165"
"ButtonAlternateFace"="181 181 181"
"ButtonDkShadow"="64 64 64"
"ButtonFace"="212 208 200"
"ButtonHilight"="255 255 255"
"ButtonLight"="212 208 200"
"ButtonShadow"="128 128 128"
"ButtonText"="0 0 0"
"GradientActiveTitle"="166 202 240"
"GradientInactiveTitle"="192 192 192"
"GrayText"="128 128 128"
"Hilight"="10 36 106"
"HilightText"="255 255 255"
"HotTrackingColor"="0 0 200"
"InactiveBorder"="212 208 200"
"InactiveTitle"="128 128 128"
"InactiveTitleText"="212 208 200"
"InfoText"="0 0 0"
"InfoWindow"="255 255 225"
"Menu"="212 208 200"
"MenuBar"="212 208 200"
"MenuHilight"="10 36 106"
"MenuText"="0 0 0"
"Scrollbar"="212 208 200"
"TitleText"="255 255 255"
"Window"="255 255 255"
"WindowFrame"="0 0 0"
"WindowText"="0 0 0"

[HKEY_CURRENT_USER\Control Panel\Colors]
"ActiveBorder"="212 208 200"
"ActiveTitle"="115 188 238"
"AppWorkSpace"="128 128 128"
"Background"="0 0 0"
"ButtonAlternateFace"="181 181 181"
"ButtonDkShadow"="106 106 106"
"ButtonFace"="240 240 240"
"ButtonHilight"="255 255 255"
"ButtonLight"="227 227 227"
"ButtonShadow"="165 165 165"
"ButtonText"="0 0 0"
"GradientActiveTitle"="115 188 238"
"GradientInactiveTitle"="158 214 250"
"GrayText"="165 165 165"
"Hilight"="231 239 245"
"HilightText"="0 0 0"
"HotTrackingColor"="59 152 211"
"InactiveBorder"="212 208 200"
"InactiveTitle"="158 214 250"
"InactiveTitleText"="150 150 150"
"InfoText"="0 0 0"
"InfoWindow"="255 255 225"
"Menu"="255 255 255"
"MenuBar"="240 240 240"
"MenuHilight"="230 230 230"
"MenuText"="0 0 0"
"Scrollbar"="212 208 200"
"TitleText"="28 28 28"
"Window"="255 255 255"
"WindowFrame"="0 0 0"
"WindowText"="0 0 0"

[HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics]
"BorderWidth"="1"
"CaptionFont"=hex:08,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,00,\
  00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"IconFont"=hex:09,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\
  00,00,01,00,00,00,00,53,00,65,00,67,00,6f,00,65,00,20,00,55,00,49,00,20,00,\
  53,00,65,00,6d,00,69,00,62,00,6f,00,6c,00,64,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"MenuFont"=hex:08,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\
  00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"MessageFont"=hex:08,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,\
  00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"ScrollHeight"="-255"
"ScrollWidth"="-255"
"SmCaptionFont"=hex:05,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,\
  00,00,00,00,01,00,00,00,00,53,00,65,00,67,00,6f,00,65,00,20,00,55,00,49,00,\
  20,00,53,00,65,00,6d,00,69,00,62,00,6f,00,6c,00,64,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"SmCaptionHeight"="-300"
"SmCaptionWidth"="-300"
"StatusFont"=hex:08,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,\
  00,00,00,00,00,00,00,22,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00' >> \$TMPFILE

echo "  - Setting DPI to 120"
echo '
[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Hardware Profiles\Current\Software\Fonts]
"LogPixels"=dword:00000078

[HKEY_CURRENT_USER\Software\Wine\Fonts]
"LogPixels"=dword:00000078

[HKEY_CURRENT_USER\Control Panel\Desktop]
"LogPixels"=dword:00000078' >> \$TMPFILE

echo "  - Disabling Wine mime associations" #see https://askubuntu.com/a/400430

echo '
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices]
"winemenubuilder"="C:\\\\windows\\\\system32\\\\winemenubuilder.exe -r"

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices]
"winemenubuilder"="C:\\\\windows\\\\system32\\\\winemenubuilder.exe -r"' >> \$TMPFILE

wine regedit \$TMPFILE

rm -f \$TMPFILE

#install some packages with winetricks for a better out-of-the-box experience
export W_OPT_UNATTENDED=1 #Avoid opening any dialog windows; install everything in unattended mode
for i in mfc42 vcrun6 vcrun2003 fontfix corefonts gdiplus msxml3 vcrun2005sp1 vcrun2008 ;do
  echo
  status "Installing \$i with winetricks..."
  winetricks \$i
done
status "Winetricks finished"

#update the wine prefix (~/.wine) to fix the issue that causes wine to not know its system drive
wine wineboot -u
#wait until above process exits
sleep 2
while [ ! -z "\$(pgrep -i 'wine C:')" ];do
  sleep 1
done
EOF

sudo chmod +x /usr/local/bin/generate-wine-prefix
/usr/local/bin/generate-wine-prefix

exit 0
