#!/bin/sh

if ! which zenity > /dev/null 2>&1; then
  echo "error: zenity was not found."
  exit 1
fi

title="Mozilla profile cleaner"

if [ -z "${HOME}" ]; then
  zenity --error --title "${title}" --text "HOME variable is not defined."
  exit 2
fi

if [ ! -d "${HOME}" ]; then
  zenity --error --title "${title}" --text "HOME directory was not found at ${HOME}."
  exit 2
fi

appname=$(zenity --list --column "ID" --column "Application" --hide-column 1 --title "${title}" --text "Select the application to clean up" "Firefox" "Mozilla Firefox" "Thunderbird" "Mozilla Thunderbird")

if [ -z "${appname}" ]; then
  zenity --info --title "${title}" --text "No application was selected."
  exit 3
fi

if [ "${appname}" = "Firefox" ]; then
  profsdir="${HOME}/.mozilla/firefox"
  appbin=firefox
else
  profsdir="${HOME}/.mozilla-thunderbird"
  appbin=thunderbird-bin
fi

if [ ! -d "${profsdir}" ]; then
  zenity --error --title "${title}" --text "${appname} profiles directory was not found at ${profsdir}."
  exit 4
fi

NL='
'
cd "${profsdir}"
profiles=$(find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n" | zenity --list --multiple --column "Profile" --separator "${NL}" --title "${title}" --text "Select one or more ${appname} profile directories")

if [ -z "${profiles}" ]; then
  zenity --info --title "${title}" --text "No ${appname} profile was selected."
  exit 5
fi

action=$(zenity --list --column "ID" --column "Action" --hide-column 1 --title "${title}" --text "Select action to perform" "cleanup" "Unlock profile (ie. clean up after a crash)" "repair" "Repair/reset profile")

if [ -z "${action}" ]; then
  zenity --info --title "${title}" --text "No action was selected."
  exit 6
fi

IFS=$NL

cleanup() {
  if [ -d "${1}" ]; then
    [ -h "${1}/lock" ] && rm -f "${1}/lock"
  fi
}

repair() {
  if [ -d "${1}" ]; then
    if [ "${appname}" = "Firefox" ]; then
      [ -d "${1}/Cache" ] && rm -rf "${1}/Cache"
      [ -d "${1}/OfflineCache" ] && rm -rf "${1}/OfflineCache"
      for file in ${1}/places.sqlite* ${1}/search.sqlite* ${1}/formhistory.sqlite*; do
        [ -f "${file}" ] && rm -rf "${file}"
      done
    else
      [ -d "${1}/ImapMail" ] && rm -rf "${1}/ImapMail"
    fi
  fi
}

user=$(id -un)
waittime=1
if killall -0 -u "${user}" "${appbin}" > /dev/null 2>&1; then
  zenity --question --title "${title}" --text "There's at least one ${appname} process running with your credentials. Should I stop it?" && killall -HUP -u "${user}" "${appbin}" > /dev/null 2>&1 && sleep ${waittime} && killall -TERM -u "${user}" "${appbin}" > /dev/null 2>&1 && sleep ${waittime} && killall -KILL -u "${user}" "${appbin}" > /dev/null 2>&1
fi

for profile in ${profiles}; do
  profdir="${profsdir}/${profile}"
  case "$action" in
    repair)
      cleanup "${profdir}"
      repair "${profdir}"
      ;;
    cleanup)
      cleanup "${profdir}"
      ;;
  esac
done

zenity --info --title "${title}" --text "Operation was successful."
exit 0


