#!/bin/sh -eu

WIDEVINE_VERSION=4.10.1196.0

if [ "x${1-}" = "x--system" ]; then
  WIDEVINE_INSTALL_DIR="/var/opt/vivaldi"
  shift 1
else
  WIDEVINE_INSTALL_DIR="$HOME/.local/lib/vivaldi"
fi

VIVALDI_INSTALL_DIR="$(dirname "$0")"

cleanup_files () {
  if [ -e "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so" ]; then
    rm "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so"
  fi
  if [ -d "$WIDEVINE_INSTALL_DIR" ]; then
    rmdir --ignore-fail-on-non-empty "$WIDEVINE_INSTALL_DIR"
  fi
  # Recreate the default symlink included in the package
  ln -fs /opt/google/chrome/libwidevinecdm.so "$VIVALDI_INSTALL_DIR/libwidevinecdm.so"
}

if [ "x${1-}" = "x--undo" ]; then
  cleanup_files
  exit
fi

case "x86_64" in
  amd64|x86_64) WIDEVINE_ARCH=x64;  WIDEVINE_SUM=866f1ae68dae1133ed70768c2e7d3ff98b4a5b88a6fa0c474d5ebbe2d5548a77 ;;
          i386) WIDEVINE_ARCH=ia32; WIDEVINE_SUM=6f08217b276eabf35ca0a32dec4477cd7e7af9a47edbcfd898eb75f071a09a9c ;;
          arm*) echo "This script does not support ARM. See https://help.vivaldi.com/article/raspberry-pi/#drm-and-flash for more information" >&2; exit ;;
esac

available () {
  command -v "$1" >/dev/null 2>&1
}

if ! available sha256sum; then
  echo "sha256sum is not installed; aborting" >&2
  exit 1
fi

if [ -e "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so" ] && echo "$WIDEVINE_SUM  $WIDEVINE_INSTALL_DIR/libwidevinecdm.so" | sha256sum -c >/dev/null 2>&1; then
  echo "Widevine ($WIDEVINE_VERSION) is already installed and does not need to be updated"
  if [ "$(readlink -f "$VIVALDI_INSTALL_DIR/libwidevinecdm.so")" != "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so" ]; then
    echo "Redirecting \"$VIVALDI_INSTALL_DIR/libwidevinecdm.so\" to \"$WIDEVINE_INSTALL_DIR/libwidevinecdm.so\""
    ln -fs "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so" "$VIVALDI_INSTALL_DIR/libwidevinecdm.so"
  fi
  exit 0
fi

if available wget; then
  DOWNLOAD="wget -qO- -T3"
elif available curl; then
  DOWNLOAD="curl -s --connect-timeout 3"
else
  echo "Neither Wget nor cURL is installed; aborting" >&2
  exit 1
fi

mkdir -p "$WIDEVINE_INSTALL_DIR"

$DOWNLOAD "https://dl.google.com/widevine-cdm/$WIDEVINE_VERSION-linux-$WIDEVINE_ARCH.zip" | gzip -d 2>/dev/null > "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so" ||:

if ! echo "$WIDEVINE_SUM  $WIDEVINE_INSTALL_DIR/libwidevinecdm.so" | sha256sum -c >/dev/null 2>&1; then
  echo "The extracted libwidevinecdm.so does not match the expected sha256sum; aborting" >&2
  cleanup_files
  exit 1
fi

ln -fs "$WIDEVINE_INSTALL_DIR/libwidevinecdm.so" "$VIVALDI_INSTALL_DIR/libwidevinecdm.so"

echo "Widevine ($WIDEVINE_VERSION) installed successfully"
