#!/bin/bash

version=5.4.53391.1108

"${DIRECTORY}/manage" install-if-not-installed 'Box86' || error "Box86 installation failed!"
if ! command -v box86 >/dev/null;then
  error "Box86 failed to install somehow!\n/usr/local/bin/box86 does not exist"
fi

# Get dependencies
install_packages libxcb-xtest0 libxcb-xfixes0 libturbojpeg0 '|' libturbojpeg || exit 1

#refresh list of libraries
sudo ldconfig

echo "Downloading Zoom..."
rm -rf "${HOME}/zoom" ~/zoom_i686.tar.xz ~/.local/share/applications/zoom.desktop /tmp/zoom_i686.tar.xz
wget -O /tmp/zoom_i686.tar.xz "https://zoom.us/client/${version}/zoom_i686.tar.xz" || wget -O /tmp/zoom_i686.tar.xz "https://zoom.com/client/${version}/zoom_i686.tar.xz" || wget -O /tmp/zoom_i686.tar.xz "https://d11yldzmag5yn.cloudfront.net/prod/${version}/zoom_i686.tar.xz" || error 'Failed to download Zoom i686!'

#get outdated Zoom client from Botspot's mirror because it's more stable
#wget -O /tmp/zoom_i686.tar.xz 'https://github.com/Botspot/zoom_686_mirror/raw/main/zoom_i686.tar.xz' || error 'Failed to download Zoom i686!'

echo "Extracting..."
sudo tar -xf /tmp/zoom_i686.tar.xz -C /opt || error 'Failed to extract Zoom xi686!'
rm -f /tmp/zoom_i686.tar.xz

#copy icon to icons dir
sudo cp "$(dirname "$0")/icon-64.png" /usr/share/icons/hicolor/64x64/apps/zoom.png
sudo update-icon-caches /usr/share/icons/*

echo "Creating a Zoom button in the Main Menu..."
echo "[Desktop Entry]
Name=Zoom
Exec=box86 /opt/zoom/zoom %u
Icon=zoom
Path=/opt/zoom/
Type=Application
Comment=x86 version of teleconferencing software, emulated with Box86
Categories=Network;
StartupNotify=true" | sudo tee /usr/share/applications/zoom.desktop >/dev/null

#Associate with mimeapp
echo "Associating Zoom mimetypes..."
xdg-mime default zoom.desktop x-scheme-handler/zoomus x-scheme-handler/zoommtg
