#!/bin/bash

#set to yes to check if installation would work for a specific version
#skips config backup, does not require chromium to be closed, avoids actually downgrading chromium
simulate=no

#Automatically determine available Chromium versions from Raspberry Pi Archive website
url_list="$(wget -O- https://archive.raspberrypi.org/debian/pool/main/c/chromium-browser/ | \
  tr '<>' '\n' | grep '^a href="chromium' | tr '"' '\n' | grep '\.deb$' | sed 's#^#https://archive.raspberrypi.org/debian/pool/main/c/chromium-browser/#g')
$(wget -O- https://archive.raspberrypi.org/debian/pool/main/c/chromium/ | \
  tr '<>' '\n' | grep '^a href="chromium' | tr '"' '\n' | grep '\.deb$' | sed 's#^#https://archive.raspberrypi.org/debian/pool/main/c/chromium/#g')"
# $url_list is a list of lines like this: "chromium-*-rpt1_arm[hf,64].deb"

#make sure $url_list contains a list
if [ -z "$url_list" ];then
  error "Failed to get a list of available Chromium versions!\nURL was: https://archive.raspberrypi.org/debian/pool/main/c/chromium-browser/"
fi

#filter it for the current architecture
architecture="$(dpkg --print-architecture)"
url_list="$(echo "$url_list" | grep "_${architecture}\.deb$\|_all\.deb$")"

if [ -z "$url_list" ];then
  error "There do not appear to be any available Chromium versions for your '$architecture' architecture."
fi

#determine the available versions of Chromium
version_list="$(echo "$url_list" | grep '/chromium-browser-l10n_\|/chromium-l10n_' | sed 's+.*/++g ; s/\..*//' | sed 's/.*_//' | sort | list_intersect "$(echo "$url_list" | grep '/chromium-browser_\|/chromium_' | sed 's+.*/++g ; s/\..*//' | sed 's/.*_//' | sort)" | sort -V | uniq)"
echo "$version_list"
#determine the main package names available. (chromium-browser, chromium-codecs-ffmpeg, etc.)
package_names="$(echo "$url_list" | sed 's+.*/++g ; s/_.*//' | sort | uniq)"
echo "$package_names"

yad_list="$(echo "$version_list" | sed 's/^/false\nChromium version /g')"

#you can run this script with a chromium version as an argument:
#usage: /path/to/this-script 78
if [ "$1" != update ];then
  version="$1"
fi

while [ -z "$version" ];do
  version="$(echo "$yad_list" | yad --center --title="Choose Chromium version" --height=290 --no-headers \
    --text="  Which Chromium version to install today?  " \
    --radiolist --list --column=Tick --column=version --separator='\n' --print-column=2 \
    --window-icon="$(dirname "$0")/icon-64.png" \
    --button=!${DIRECTORY}/icons/check.png!OK:0)"
  button=$?
  
  [ $button != 0 ] && error "User error: exited chromium version selection list"
  
  #get just chromium version NUMBER
  version="$(echo "$version" | awk '{print $3}')"
done

#generate a flexible list of urls to download based on the version number
 #chromium-browser was renamed to chromium in newer versions
  #codecs-ffmpeg-extra package is not used in newer versions
   #chromium-common is needed in newer versions
package_names='chromium
chromium-l10n
chromium-common
chromium-browser
chromium-browser-l10n
chromium-codecs-ffmpeg-extra'
for package in $package_names; do
  if echo "$url_list" | grep -q "/${package}_${version}\." ;then
    if [ "$package" == chromium-browser ] && [[ "${download_urls[*]}" == *'/chromium_'* ]];then
      true #avoid downloading chromium-browser dummy package if chromium package is the real one
    elif [ "$package" == chromium-browser-l10n ] && [[ "${download_urls[*]}" == *'/chromium-l10n_'* ]];then
      true #avoid downloading chromium-browser dummy package if chromium package is the real one
    else
      #if the debs are built for both bookworm and trixie, get the appropriate one
      url="$(echo "$url_list" | grep "/${package}_${version}\.")" #has multiple lines
      if [[ "$url" == *deb12* ]] && [[ "$url" == *deb13* ]];then
        if [ "$(get_codename)" == trixie ];then
          url="$(echo "$url" | grep deb13)"
        else
          url="$(echo "$url" | grep deb12)"
        fi
      fi
      #now version-sort to get the last rpt build of this chromium package version
      download_urls+=("$(echo "$url" | sort -Vr | head -n1)")
    fi
  fi
done

if ! echo "${download_urls[*]}" | grep -q '/chromium_\|/chromium-browser_' ;then
  error "Failed to determine the url for chromium-browser!\nChosen version was '$version'\nurl_list was:\n'$url_list'"
fi

echo "Debs to install:
${download_urls[*]}"

#wait until chromium is not running
if [ ! -z "$(ps aux | grep chromium | grep -v 'grep' )" ] && [ "$simulate" != yes ];then
  echo -n "Please close all Chromium windows first."
  yad --info --center --window-icon="$(dirname "$0")/icon-64.png" \
  --title="Close Chromium first" --text="$(echo -e "  Chromium is running.\n  To reduce the risk of Chromium profile corruption, please close Chromium first.  ")" \
  --window-icon="$(dirname "$0")/icon-64.png" --no-buttons &
  yadpid=$!
  while [ ! -z "$(ps aux | grep chromium | grep -v 'grep' )" ];do
    echo -n '.'
    sleep 1
  done
  echo
  kill $yadpid
fi

#back up chromium config directory
if [ ! -d ~/.config/chromium.bak ] && [ -d ~/.config/chromium ] && [ "$simulate" != yes ];then
  echo "Backing up existing Chromium profile directory..."
  rm -rf ~/.config/chromium.bak
  
  cp -a ~/.config/chromium ~/.config/chromium.bak
fi

#download the files
status "Downloading the packages..."
for download_url in ${download_urls[*]} ;do
  filename="/tmp/$(basename "$download_url")"
  rm -f "$filename" || error "Failed to first remove $filename"
  wget -O "$filename" "$download_url" || exit 1
  filenames+=("$filename")
done

#modern Pi OS transitioned from libraspberrypi0 to libdtovl0, but old chromium depends on libraspberrypi0.
#Modify deb packages to remove this dependency
for filename in ${filenames[*]} ;do
  if dpkg-deb -I "$filename" | grep -q 'Depends:.*libraspberrypi0' ;then
    #this package needs to be patched to not depend on libraspberrypi0
    status "Patching $(basename "$filename") package to not depend on libraspberrypi0..."
    patch_deb_sed "$filename" 's/, libraspberrypi0//g ; s/libraspberrypi0//g'
    status_green Done
  fi
done

#identify conflicting packages when transitioning across the chromium <--> chromium-browser divide
conflicts=''
if package_installed chromium && [[ "${download_urls[*]}" == *'/chromium-browser_'* ]];then
  conflicts='chromium chromium-common chromium-l10n'
elif package_installed chromium-browser && [[ "${download_urls[*]}" == *'/chromium_'* ]];then
  conflicts='chromium-browser chromium-codecs-ffmpeg-extra chromium-browser-l10n'
fi

if [ "$simulate" == yes ];then
  status "Simulating installing the packages..."
  if [ ! -z "$conflicts" ];then
    warning "Simulation will likely complain about these conflicting packages: $conflicts\nA real run would purge these packages first."
  fi
  
  status_green "Running command: apt install --simulate -f --allow-downgrades --allow-change-held-packages ${filenames[*]}"
  apt install --simulate -f --allow-downgrades --allow-change-held-packages  "${filenames[@]}" || error "APT reported a failure during simulated package installation.\nDeb files have not been removed, so feel free to try tweaking the apt command to see what could be done to make it work."
else
  if [ ! -z "$conflicts" ];then
    status "Removing conflicting packages: $conflicts"
    sudo apt purge -y --allow-change-held-packages $conflicts || error "APT failed to first purge conflicting chromium packages: $conflicts"
  fi
  
  status "Installing the packages..."
  apt_lock_wait
  sudo apt install -yf --allow-downgrades --allow-change-held-packages "${filenames[@]}" || error "APT failed to install the packages: ${filenames[*]}"
fi
rm -f "${filenames[@]}" || error "Failed to remove packages after installation"

if [ "$simulate" != yes ];then
  status "Holding Chromium version so it won't upgrade..."
  for filename in ${filenames[*]} ;do
    package_name="$(basename "$filename" | sed 's/_.*//g')"
    apt_lock_wait
    echo "$package_name hold" | sudo dpkg --set-selections
  done
fi

if [ "$version" -le 88 ] && [ "$(get_codename)" == 'bullseye' ];then
  status "Fixing seccomp errors for Chromium $version on Bullseye..."
  echo "Creating an override file at /etc/chromium-browser/customizations/01-disable-seccomp"
  echo 'CHROMIUM_FLAGS="${CHROMIUM_FLAGS} --disable-seccomp-filter-sandbox"' | sudo tee /etc/chromium-browser/customizations/01-disable-seccomp
elif [ "$version" -le 92 ] && [ "$(get_codename)" == 'trixie' ];then
  status "Fixing seccomp errors for Chromium $version on Trixie..."
  echo "Creating an override file at /etc/chromium-browser/customizations/01-disable-seccomp"
  echo 'CHROMIUM_FLAGS="${CHROMIUM_FLAGS} --disable-seccomp-filter-sandbox"' | sudo tee /etc/chromium-browser/customizations/01-disable-seccomp
fi

#echo "Fixing Chromium profile..."
#rm ~/'.config/chromium/Default/Web Data' &>/dev/null
