#!/bin/bash

# Get parameters
QUIET=false
DELETE=false
while getopts ":qd" opt; do
  case $opt in
    q)
      QUIET=true
      ;;
    d)
      DELETE=true
      ;;
    *)
      echo "Possible parameters:"
      echo "-q      Quiet: no messages"
      echo "-d      Delete: rename userChrome.css"
      exit 1
      ;;
  esac
done

# Check if Thunderbird is installed
if [ -z "$(which thunderbird)" ]; then
  echo 'Thunderbird is not installed - exiting'
  exit 2
fi

if [ -z "$(ls /usr/share/icons/evolvere*/index.theme)" ]; then
  echo 'Evolvere icon theme is not installed - exiting'
  exit 3
fi

# Wait for profiles.ini to be created by Thunderbird
TB="$HOME/.thunderbird"
if [ ! -e "$TB/profiles.ini" ]; then
  echo 'Start Thunderbird to create profiles.ini file'
  if ! $QUIET; then 
    zenity --info --timeout=3 --text='Start Thunderbird to create profiles.ini file'
  fi
  inotifywait -q -m -r "$HOME" -e close_write --format '%w%f' |
  while read NEWFILE; do
    if [ "$NEWFILE" == "$TB/profiles.ini" ]; then
      echo "$TB/profiles.ini has been written"
      pkill -f "inotifywait -q -m -r $HOME"
    fi
  done
fi

# If user kills inotifywait: exit
if [ ! -e "$TB/profiles.ini" ]; then
  echo 'Thunderbird has not been initialized - exiting.'
  exit 4
fi

TBPROFILE=$TB/$(grep Path "$TB/profiles.ini" | cut -d = -f 2)
TBCSS="$TBPROFILE/chrome/userChrome.css"
DT="$HOME/.config/autostart/tb-icons.desktop"
CLEANUP=false

# Check installed theme
if [ -f  "$TBCSS" ]; then
  if $DELETE; then
    # Rename
    mv "$TBCSS" "$TBCSS.bak"
    exit 0
  else
    # Check for evolvere-light theme
    ISLIGHT=$(grep evolvere-light "$TBCSS")
  fi
fi

if [ -z "$ISLIGHT" ]; then
  # Not installed or dark theme in use
  ANSWER=true
  if ! $QUIET; then
    # Ask the user what to do
    zenity --question --text='Thunderbird Evolvere Icon Theme\n\nInstall theme?'
    if [ "$?" -gt 0 ]; then ANSWER=false; fi
  fi
  if $ANSWER; then
    if [ ! -f "$TBCSS" ]; then
      # Fresh install
      cp -r /usr/share/solydxk/thunderbird/chrome "$TBPROFILE"
      CLEANUP=true
    else
      # Switch to light theme
      sed -i 's/evolvere-dark/evolvere-light/g' "$TBCSS"
      CLEANUP=true
    fi
    if ! $QUIET; then
      zenity --info --text="Thunderbird Evolvere Light Theme installed to:\n\n$TBPROFILE"
    fi
  fi
else
  # Light theme in use
  if zenity --question --text='Thunderbird Evolvere Icon Theme\n\nInstall dark theme?'; then
    # Switch to dark theme
    sed -i 's/evolvere-light/evolvere-dark/g' "$TBCSS"
    zenity --info --text="Thunderbird Evolvere Dark Theme installed to:\n\n$TBPROFILE"
    CLEANUP=true
  fi
fi

# Make sure the autstart file is removed
if $CLEANUP && [ -f "$DT" ]; then rm "$DT"; fi

exit 0
