#!/usr/bin/env bash

# omarchy:summary=Install Oh My Git!, the game that teaches git
# omarchy:requires-sudo=true

# Based: the builds Based publishes: the zip into /opt/oh-my-git on amd64,
# the pinned arm64 binary checked against its sha256, with an icon and a
# desktop entry; the macOS zip unpacks into /Applications.

set -eo pipefail

bucket=https://s3.eu-west-3.amazonaws.com/public.bitspur.com/binaries/oh-my-git
arm64_sha256=d750866ce4e5f5b72bd9b8ba3048a9a171eede9288411e27bedd119ffecac08e

echo "Installing Oh My Git!..."

case $(omarchy-os) in
darwin)
  if [[ ! -d "/Applications/Oh My Git.app" ]]; then
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    curl -fL --progress-bar "$bucket/oh-my-git-osx.zip" -o "$tmp/oh-my-git.zip"
    unzip -qo "$tmp/oh-my-git.zip" -d "$tmp"
    mv "$tmp/Oh My Git!.app" "/Applications/Oh My Git.app"
  fi
  ;;
*)
  if [[ ! -x /opt/oh-my-git/bin/oh-my-git ]]; then
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    sudo mkdir -p /opt/oh-my-git/bin
    case $(dpkg --print-architecture) in
    amd64)
      curl -fL --progress-bar "$bucket/oh-my-git-linux.zip" -o "$tmp/oh-my-git.zip"
      unzip -qo "$tmp/oh-my-git.zip" -d "$tmp"
      sudo install -m 755 "$tmp/oh-my-git" /opt/oh-my-git/bin/oh-my-git
      sudo install -m 644 "$tmp/oh-my-git.pck" /opt/oh-my-git/bin/oh-my-git.pck
      ;;
    arm64)
      curl -fL --progress-bar "$bucket/oh-my-git-linux-aarch64" -o "$tmp/oh-my-git"
      echo "$arm64_sha256  $tmp/oh-my-git" | sha256sum -c -
      sudo install -m 755 "$tmp/oh-my-git" /opt/oh-my-git/bin/oh-my-git
      ;;
    *)
      echo "Oh My Git! has no Linux build for $(dpkg --print-architecture); nothing to install"
      exit 0
      ;;
    esac
    curl -fsSL https://ohmygit.org/assets/images/oh-my-git.png -o "$tmp/icon.png"
    sudo install -m 644 "$tmp/icon.png" /opt/oh-my-git/icon.png
  fi
  sudo mkdir -p /usr/local/share/applications
  sudo tee /usr/local/share/applications/oh-my-git.desktop >/dev/null <<'DESKTOP'
[Desktop Entry]
Version=1.0
Name=Oh My Git
Comment=An open source game about learning Git
Exec=/opt/oh-my-git/bin/oh-my-git
Icon=/opt/oh-my-git/icon.png
Type=Application
Categories=Development;Game;Education;
DESKTOP
  ;;
esac
