#!/bin/bash

# use unofficial source to download CrazyCattle3D resources
# reason is itch.io page does not allow direct downloads unless you use a 3rd party tool
# like itch-dl which requires API keys to work
status "Downloading game resources..."
wget https://zip.crazycattle3d.com/CrazyCattle3DLinux.zip -O /tmp/CrazyCattle3DLinux.zip

status "Downloading the Godot game engine runtime for your platform..."

# Godot does not offer runtimes in their releases page as seperate binaries, instead it is as a large archive
# This will have to download a large export template and extract the desired binary
sudo mkdir -p /opt/crazycattle3d
# for now use my repo of seperated Godot export template builds until these files exist in the Pi-Apps-Coders/files repo
case "$arch" in
  "64") sudo wget https://github.com/matu6968/godotengine-templates/releases/download/4.4.1-stable/linux_release.arm64 -O /opt/crazycattle3d/CrazyCattle3D || error "Failed to download Godot game engine!" ;;
  "32") sudo wget https://github.com/matu6968/godotengine-templates/releases/download/4.4.1-stable/linux_release.arm32 -O /opt/crazycattle3d/CrazyCattle3D || error "Failed to download Godot game engine!" ;;
  *) error "arch variable is not set, cannot continue" ;;
esac

unzip /tmp/CrazyCattle3DLinux.zip CrazyCattle3D.pck -d /tmp || error "Failed to extract game resources!"
sudo mv /tmp/CrazyCattle3D.pck /opt/crazycattle3d/CrazyCattle3D.pck || error "Failed to move game resources from /tmp!"
sudo cp "$(dirname "$0")/icon-64.png" /opt/crazycattle3d || error "Failed to copy CrazyCattle3D icon to /opt/crazycattle3d!"

# Make command asociations
status "Making terminal command..."
echo '#!/bin/bash
/opt/crazycattle3d/CrazyCattle3D --rendering-driver opengl3_es "$@"' | sudo tee /usr/local/bin/crazycattle3d >/dev/null
sudo chmod +x /usr/local/bin/crazycattle3d || error "Failed to make terminal command executable!"
sudo chmod +x /opt/crazycattle3d/CrazyCattle3D || error "Failed to make binary executable!"

# Make menu launcher
status "Making menu launcher..."
echo "[Desktop Entry]
Name=CrazyCattle3D
Comment=A battle royale rage game about sheep; will you have what it takes to survive?
Exec=crazycattle3d %f
Icon=/opt/crazycattle3d/icon-64.png
Terminal=false
Type=Application
Categories=Game;" | sudo tee /usr/local/share/applications/crazycattle3d.desktop >/dev/null

status "Cleaning up..."
sudo rm -f /tmp/CrazyCattle3DLinux.zip
