#!/bin/bash

set -eu

SCRIPT_PATH=$(dirname "${BASH_SOURCE[0]}")
CACHE_FILE_PATH="$SCRIPT_PATH/.discord_version_cache"

CURRENT_VERSION=$(curl -s "https://discord.com/api/updates/canary?platform=linux" | jq -r .name)
INSTALLED_VERSION=""

if test -f "$CACHE_FILE_PATH"; then
  INSTALLED_VERSION=$(head -n 1 "$CACHE_FILE_PATH")
fi

if [ "$CURRENT_VERSION" != "$INSTALLED_VERSION" ]; then
  echo "New version $CURRENT_VERSION found. Downloading..."
  curl -Ls -o /tmp/discord-canary.deb "https://discord.com/api/download/canary?platform=linux&format=deb"
  if [ ${1-default} != "--download-only" ]; then
    pkexec apt install -y /tmp/discord-canary.deb
    rm /tmp/discord-canary.deb
  fi
  echo $CURRENT_VERSION > $CACHE_FILE_PATH
else
  echo "Current version is already installed."
  if [ ${1-default} == "--download-only" ]; then
    exit 2
  fi
fi
