#!/bin/sh
# Installs or updates a local (single user) install of @@SET_STREAM@@

# Exit at the first sign of problems
set -eu

# Set stream
VIVALDI_STREAM="@@SET_STREAM@@"
VIVALDI_SHORT_STREAM="${VIVALDI_STREAM%-stable}"

# Don't bother checking if we already checked within the last 10 minutes
DATE_10_BACK="$(mktemp -t ${VIVALDI_STREAM}-updater-10-back.XXXXXX)"
touch -d "@$(expr $(date +%s) - 600)" "$DATE_10_BACK"
if [ -n "$(find "${TMP:-/tmp}" -maxdepth 1 -newer "$DATE_10_BACK" -name ${VIVALDI_STREAM}-updater-last-check -print)" ]; then
  echo "A check for a new version was performed less than 10 minutes ago" >&2
  rm -f "$DATE_10_BACK"
  exit
else
  touch "${TMP:-/tmp}/${VIVALDI_STREAM}-updater-last-check"
  rm -f "$DATE_10_BACK"
fi

# Set architecture
ARCHITECTURE="$(uname -m)"
case "$ARCHITECTURE" in
   x86_64) DEBIAN_ARCHITECTURE=amd64; VIVALDI_ARCHITECTURE=x64 ;;
     arm*) DEBIAN_ARCHITECTURE=armhf; VIVALDI_ARCHITECTURE=arm ;;
  aarch64) DEBIAN_ARCHITECTURE=arm64; VIVALDI_ARCHITECTURE=arm64 ;;
        *) echo "The architecture $ARCHITECTURE is not supported." >&2 ; exit 1 ;;
esac

# Make sure we have Wget or cURL for downloading
available () {
  command -v "$1" >/dev/null 2>&1
}
if available wget; then
  DL_SILENT="wget -qO-"
  DL_LOUD="wget"
  DL_OUTPUT="-O"
elif available curl; then
  DL_SILENT="curl -fs"
  DL_LOUD="curl -f"
  DL_OUTPUT="-o"
else
  echo "You need to install Wget or cURL to retrieve the latest version of $VIVALDI_SHORT_STREAM for $ARCHITECTURE; exiting" >&2
  exit 1
fi

# Use the Apt repository to find the latest version number
VIVALDI_VERSION=$($DL_SILENT "https://repo.vivaldi.com/archive/deb/dists/stable/main/binary-$DEBIAN_ARCHITECTURE/Packages.gz" | gzip -d | grep -A6 -x "Package: $VIVALDI_STREAM" | sed -n 's/^Version: \(\([0-9]\+\.\)\{3\}[0-9]\+\).*/\1/p' | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n | tail -n 1)
if [ -z "VIVALDI_VERSION" ]; then
  echo "Cannot work out the latest version of $VIVALDI_STREAM; exiting" >&2
  exit 1
fi

# Fetch package if we do not already have it installed
if [ -e "${XDG_DATA_HOME:-$HOME/.local/share}/$VIVALDI_SHORT_STREAM/VERSION_$VIVALDI_VERSION" ]; then
  echo "You already have $VIVALDI_SHORT_STREAM version $VIVALDI_VERSION installed"
  exit
fi
VIVALDI_PKG_DIR="$(mktemp -td ${VIVALDI_SHORT_STREAM}-${VIVALDI_VERSION}_TMPDIR.XXXXXX)"
VIVALDI_PACKAGE="${VIVALDI_STREAM}-${VIVALDI_VERSION}-${VIVALDI_ARCHITECTURE}.tar"
$DL_LOUD "https://downloads.vivaldi.com/${VIVALDI_STREAM#*-}-auto/$VIVALDI_PACKAGE" "$DL_OUTPUT" "$VIVALDI_PKG_DIR/$VIVALDI_PACKAGE"

# Unpack and install
tar xfC "$VIVALDI_PKG_DIR/$VIVALDI_PACKAGE" "$VIVALDI_PKG_DIR"
sh -eu "$VIVALDI_PKG_DIR/${VIVALDI_PACKAGE%.tar}/install" ||:

# Remove package
rm -r "$VIVALDI_PKG_DIR"
