#!/bin/bash

version=2026.08.08
INSTALL_DIR="$HOME/.local/share"

rm -f /tmp/tbb-nightly.tar.xz
wget -O /tmp/tbb-nightly.tar.xz "https://nightlies.tbb.torproject.org/nightly-builds/tor-browser-builds/tbb-nightly.$version/nightly-linux-aarch64/tor-browser-linux-aarch64-tbb-nightly.$version.tar.xz" || error "Failed to download Tor Browser Nightly ver. $version"

status -n 'Looking for previous installations and remaining user data… '
if [ -d "$INSTALL_DIR"/tor-browser ]; then
  #if data folder exists, prepare to import its user-data
  if [ -d "$INSTALL_DIR"/tor-browser/Browser/TorBrowser/Data/Browser ];then
    mv -f "$INSTALL_DIR"/tor-browser/Browser/TorBrowser/Data/Browser/ "$INSTALL_DIR"/tor-browser.temp/ || error 'Failed to move existing user data to temporary folder'
  fi
  rm -rf "$INSTALL_DIR"/tor-browser/* || error 'Failed to remove old Tor Browser files'
else
  mkdir -p "$INSTALL_DIR"/tor-browser || error 'Failed to create installation directory'
fi
status_green 'Done'

status -n "Extracting Tor Browser to $INSTALL_DIR/tor-browser … "
tar -xpJf /tmp/tbb-nightly.tar.xz -C "$INSTALL_DIR"/tor-browser --strip-components=1 || error 'Failed to extract Tor Browser'
rm -f /tmp/tbb-nightly.tar.xz
status_green 'Done'

#if tor-browser.temp folder exists, import its user-data
if [ -d "$INSTALL_DIR"/tor-browser.temp ];then
  status -n 'Importing existing user data… '
  rm -rf "$INSTALL_DIR"/tor-browser/Browser/TorBrowser/Data/Browser
  mv -f "$INSTALL_DIR"/tor-browser.temp "$INSTALL_DIR"/tor-browser/Browser/TorBrowser/Data/Browser
  rm -rf "$INSTALL_DIR"/tor-browser.temp
  status_green 'Done'
fi

status -n 'Registering Tor Browser as a desktop app for this user… '
cd "$INSTALL_DIR"/tor-browser || error 'Fatal error! Cannot cd to app!'
"$INSTALL_DIR"/tor-browser/start-tor-browser.desktop --register-app || error 'Failed to register a desktop app'

#copy icon for wf-panel
mkdir -p ~/.local/share/icons
cp -f "$INSTALL_DIR"/tor-browser/Browser/browser/chrome/icons/default/default128.png ~/.local/share/icons/tor-browser.png

#edit start script to make it run on wayland, and with an app-id that matches the icon
sed -i "s+^Exec=.*+Exec=env MOZ_ENABLE_WAYLAND=1 ${INSTALL_DIR}/tor-browser/Browser/start-tor-browser --class 'tor-browser' --name 'tor-browser'+g" ~/.local/share/applications/start-tor-browser.desktop

status_green 'Done'
