#!/bin/bash

sudo rm -f /usr/share/keyrings/brave-browser-archive-keyring.gpg
sudo rm -f /etc/apt/sources.list.d/brave-browser-release.list
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/brave-browser-archive-keyring.gpg] https://brave-browser-apt-release.s3.brave.com/ stable main" | sudo tee /etc/apt/sources.list.d/brave-browser-release.list
if ! sudo wget -O /usr/share/keyrings/brave-browser-archive-keyring.gpg https://brave-browser-apt-release.s3.brave.com/brave-browser-archive-keyring.gpg ;then
  sudo rm -f /etc/apt/sources.list.d/brave-browser-release.list /usr/share/keyrings/brave-browser-archive-keyring.gpg
  error "Failed to download keyring for brave-browser. brave-browser repository has been removed."
fi

(install_packages brave-browser)
if [ $? != 0 ]; then
  if ! anything_installed_from_uri_suite_component "https://brave-browser-apt-release.s3.brave.com/" stable main ; then
    # nothing installed from repo, this check is to prevent removing repos which other pi-apps scripts or the user have used successfully
    # safe to remove
    sudo rm -f /etc/apt/sources.list.d/brave-browser-release.list /usr/share/keyrings/brave-browser-archive-keyring.gpg
    error "Failed to install brave-browser. brave-browser repository has been removed."
  else
    error "Failed to install brave-browser."
  fi
fi

#detect if Widevine can be enabled
if package_available libwidevinecdm0;then
  description="Make Widevine DRM (for Netflix, Spotify) available to Brave?

You will still need to enable Widevine inside of Brave in brave://settings/extensions"
  userinput_func "$description" "Yes, make Widevine DRM available" "No, do not make Widevine DRM available."
  if [ "$output" == "Yes, make Widevine DRM available" ]; then
    install_packages libwidevinecdm0 || exit 1
  fi
fi

# make widevine available if it is installed
if [ -d /opt/chromium.org/chromium/WidevineCdm ]; then
  sudo rm -rf /opt/brave.com/brave/WidevineCdm
  sudo ln -s /opt/chromium.org/chromium/WidevineCdm /opt/brave.com/brave/WidevineCdm || error "Could not create WidevineCdm symlink"
elif [ -d /opt/WidevineCdm ]; then
  sudo rm -rf /opt/brave.com/brave/WidevineCdm
  sudo ln -s /opt/WidevineCdm /opt/brave.com/brave/WidevineCdm || error "Could not create WidevineCdm symlink"
fi
