#!/bin/bash

mkdir -p /etc/root 2> /dev/null
rootperm=$?
if [ $rootperm -eq 0 ] ; then
  rm -rf /etc/root
else
  echo "Root permission is required to run this script"
  exit
fi

install_icecat_gen() {
  download_url_icecat="${1}"
  echo "Downloading icecat"
  rm -rf /tmp/icecat.tar.xz
  wget -q --show-progress -c "https://icecatbrowser.org${download_url_icecat}" -O /tmp/icecat.tar.xz
  echo "Installing icecat"
  if [ -d /usr/lib ] ; then
    tar Jxf /tmp/icecat.tar.xz -C /usr/lib/
    unlink /usr/bin/icecat 2> /dev/null
    install_icecat_desktop
    ln -s /usr/lib/icecat/icecat /usr/bin/icecat
    chmod +x /usr/bin/icecat
  fi
  rm -rf /tmp/icecat.tar.xz
  echo "Installation icecat done"
}

install_icecat_desktop() {
  if [ -d /usr/share/applications ] ; then
    echo '[Desktop Entry]' > /usr/share/applications/icecat.desktop
    echo 'Name=GNU Icecat' >> /usr/share/applications/icecat.desktop
    echo 'Comment=Browse the World Wide Web' >> /usr/share/applications/icecat.desktop
    echo 'GenericName=Web Browser' >> /usr/share/applications/icecat.desktop
    echo 'X-GNOME-FullName=GNU Icecat Web Browser' >> /usr/share/applications/icecat.desktop
    echo 'Exec=/usr/lib/icecat/icecat-bin %u' >> /usr/share/applications/icecat.desktop
    echo 'Terminal=false' >> /usr/share/applications/icecat.desktop
    echo 'X-MultipleArgs=false' >> /usr/share/applications/icecat.desktop
    echo 'Type=Application' >> /usr/share/applications/icecat.desktop
    if [ -f /usr/lib/icecat/browser/chrome/icons/default/default48.png ] ; then
      echo 'Icon=/usr/lib/icecat/browser/chrome/icons/default/default48.png' >> /usr/share/applications/icecat.desktop
    else
      echo 'Icon=icecat' >> /usr/share/applications/icecat.desktop
    fi
    echo 'Categories=Network;WebBrowser;' >> /usr/share/applications/icecat.desktop
    echo 'MimeType=text/html;text/xml;application/xhtml+xml;application/xml;application/vnd.mozilla.xul+xml;application/rss+xml;application/rdf+xml;image/gif;image/jpeg;image/png;x-scheme-handler/http;x-scheme-handler/https;' >> /usr/share/applications/icecat.desktop
    echo 'StartupWMClass=Firefox' >> /usr/share/applications/icecat.desktop
    echo 'StartupNotify=true' >> /usr/share/applications/icecat.desktop
  fi
}

echo "Checking icecat version"
touch /etc/icecat_version.conf
url_download=$(curl -s "https://icecatbrowser.org/all_downloads.html" | grep "linux-x86_64.tar" | head -1 | grep -oP 'href="\K[^"]+')
version_icecat=$(echo "${url_download}" | grep -oP '(?<=/icecat/)[^/]+')
version_icecat_current=$(cat /etc/icecat_version.conf)
if [ "${version_icecat}" != "${version_icecat_current}" ] ; then
  echo "New icecat version detected"
  install_icecat_gen "${url_download}"
  error_install=$?
  if [ ${error_install} -eq 0 ] ; then
    echo "${version_icecat}" > /etc/icecat_version.conf
  fi
else
  echo "No updates for icecat"
fi
