#!/usr/bin/env bash
app_name=Nuke
download_from_source=$1
version=$2

if [ -z "$version" ]; then
  version="15.1v3"
fi

vnum="${version%%v*}"
installer_path=~/Downloads/Nuke${version}-linux-x86_64.run

base_url=https://public.noisyserver.sbs/vfx-installers
url=${base_url}/Nuke${version}-linux-x86_64.run

nuke_install_basepath=/usr/bin/Nuke
installation_dir_name=Nuke${version}

if [ -f "${installer_path}" ]; then
  download_from_source=s
  echo "Installer file already exists"
fi
# echo "${url} -> ${installer_path}"
if [ -z "$download_from_source" ]; then
  read -p "Press Enter to start download of ${app_name} ${version}. If file is already downloaded enter 's', or 'c' to cancel: " download_from_source
fi

delete_installer=0

case $download_from_source in
[Ss]*)
  echo "Skipped download (if the install fails, check that the installer was downloaded properly)"
  ;;
[CcNn]*)
  echo "Installation cancelled"
  exit 0
  ;;
*)
  echo "Downloading ${app_name} Installer..."
  curl -# -o ${installer_path}.partial ${url}
  rm ${installer_path} >>/dev/null
  mv ${installer_path}.partial ${installer_path}
  read -p "Download Finished. Press Enter to continue: "
  delete_installer=1
  ;;
esac

sudo chmod +x ${installer_path}
# sudo ${installer_path}

sudo ${installer_path} --accept-foundry-eula

echo "Moving application to bin directory..."
if [ ! -d "${nuke_install_basepath}" ]; then
  sudo mkdir ${nuke_install_basepath} >/dev/null
fi
sudo rm -r ${nuke_install_basepath}/${installation_dir_name}
sudo mv ./${installation_dir_name} ${nuke_install_basepath}/
curl -sS -# -o ./nuke.png ${base_url}/nuke.png
sudo mv nuke.png ${nuke_install_basepath}/nuke.png

echo "Installing libraries..."
sudo yum install mesa-libGLU.x86_64 -y
sudo dnf install libxcrypt-compat -y

echo "Creating Application shortcut..."
sudo mkdir -p ~/.local/share/applications/
sudo chmod -R 777 ~/.local/share/applications/
cd ~/.local/share/applications/
echo "#!/usr/bin/env xdg-open
[Desktop Entry]
Version=1.0
Terminal=false
Type=Application
Name=Nuke ${version}
Exec=${nuke_install_basepath}/${installation_dir_name}/Nuke${vnum} --indie
Icon=${nuke_install_basepath}/nuke.png" >${installation_dir_name}.desktop

echo "Cleanup..."
if [ "${delete_installer}" = 1 ]; then
  echo "deleting downloaded installer..."
  rm ${installer_path}
  sudo rm -r ./Nuke${version} >>/dev/null
else
  echo "leaving previously-existing installer in place..."
fi
echo "${app_name} installation script finished"
