#!/bin/sh

set -eu

command=$1
shift

version=149.0.2

urlbase="https://download-installer.cdn.mozilla.net/pub/firefox/releases/${version}/linux-x86_64"

setup_firefox_wrapper() {
  cat <<'EOF' > /usr/local/bin/firefox
#!/bin/sh

set -eu

case "$LANG" in
  de_*) firefox_dir=/opt/firefox/de    ;;
  fi_*) firefox_dir=/opt/firefox/fi    ;;
  fr_*) firefox_dir=/opt/firefox/fr    ;;
  sv_*) firefox_dir=/opt/firefox/sv-SE ;;
  uk_*) firefox_dir=/opt/firefox/uk    ;;
  *)    firefox_dir=/opt/firefox/en-GB ;;
esac

# This is needed since Firefox 68, otherwise each language installation
# (and Firefox 68 from Mozilla binaries compared to old Firefox binaries
# from Ubuntu) will have their own profile (and users are missing bookmarks
# and such).
export MOZ_LEGACY_PROFILES=1

is_libcamerify_installed=false
if which libcamerify >/dev/null; then
  is_libcamerify_installed=true
fi

is_libcamerify_enabled=false
if puavo_libcamerify_enabled="$(puavo-conf puavo.libcamerify.enabled)"; then
  if [ "${puavo_libcamerify_enabled}" = 'true' ]; then
     is_libcamerify_enabled=true
  fi
fi

# On hosts which have libcamerify installed and enabled, use it to
# make complex camera devices available to Firefox via V4L2 compat
# library (libcamerify defines LD_PRELOAD and execs Firefox).
if ${is_libcamerify_installed} && ${is_libcamerify_enabled}; then
  exec libcamerify "${firefox_dir}/firefox" "$@"
else
  exec "${firefox_dir}/firefox" "$@"
fi
EOF
  chmod 755 /usr/local/bin/firefox
}

case "${command}" in
  configure)
    upstream_dir=$1
cat <<'EOF' > /usr/share/applications/firefox.desktop.tmp
[Desktop Entry]
Name=Firefox
Comment=Web Browser
GenericName=Web Browser
X-GNOME-FullName=Firefox Web Browser
Exec=/usr/local/bin/firefox %u
Terminal=false
X-MultipleArgs=false
Type=Application
Icon=/opt/firefox/en-GB/browser/chrome/icons/default/default128.png
Categories=Network;WebBrowser;
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;
StartupWMClass=Firefox
StartupNotify=true

Actions=new-window;PrivateBrowsing

[Desktop Action new-window]
Name=New Window
Name[fi]=Uusi ikkuna
Name[de]=Neues Fenster
Name[sv]=Nytt fönster
Exec=/usr/local/bin/firefox --new-window %u

[Desktop Action PrivateBrowsing]
Name=New Private Browsing Window
Name[fi]=Uusi yksityisen selauksen ikkuna
Name[de]=Neues privates Fenster
Name[sv]=Nytt privat fönster
Exec=/usr/local/bin/firefox --private-window %u

EOF
    mv /usr/share/applications/firefox.desktop.tmp \
       /usr/share/applications/firefox.desktop

    ln -fns "$upstream_dir" /opt/firefox

    setup_firefox_wrapper

    update-alternatives --install /usr/bin/x-www-browser x-www-browser \
                        /usr/local/bin/firefox 200
    update-alternatives --set x-www-browser /usr/local/bin/firefox
    ;;

  unconfigure)
    if pgrep -f '/opt/firefox/.*/firefox' > /dev/null 2>&1; then
      echo 'Firefox is running, will not unconfigure' >&2
      # 4 == application is busy
      exit 4
    fi
    update-alternatives --remove x-www-browser /usr/local/bin/firefox
    rm -f /opt/firefox \
          /usr/local/bin/firefox \
          /usr/share/applications/firefox.desktop
    ;;

  unpack)
    upstream_pack=$1
    upstream_dir=$2

    tar --no-same-owner -jx -f "$upstream_pack" -C "$upstream_dir"
    ;;

  download)
    upstream_pack=$(readlink -f "$1")
    tmpdir=
    trap '[ -n "$tmpdir" ] && rm -rf "$tmpdir"' 0 INT TERM
    tmpdir=$(mktemp -d)

    firefox_checksums_path="$(pwd)/firefox_checksums.txt"

    (
      cd "$tmpdir"
      new_checksums_path="${tmpdir}/new_firefox_checksums.txt"
      if [ "${PUAVOPKG_DEVMODE:-}" = 'true' ]; then
        cat /dev/null > "$new_checksums_path"
      fi
      while read sha384 lang_dir; do
        tarpath="${lang_dir}/firefox-${version}.tar.xz"
        tarfile="$(basename "$tarpath")"
        wget \
            --no-use-server-timestamps \
            --no-cookies \
            --output-document "$tarfile" \
            --progress=dot:mega \
            "${urlbase}/${tarpath}" || {
            [ $? -eq 4 ] && exit 2 ## Network failure.
            exit 1
        }
        if ! echo "${sha384} ${tarfile}" | sha384sum --check >/dev/null; then
          actual_checksum=$(sha384sum "$tarfile" | awk '{ print $1 }')
          if [ "${PUAVOPKG_DEVMODE:-}" != 'true' ]; then
            echo "checksum NOT matching for $tarpath" >&2
            echo "expected: ${sha384} / actual: ${actual_checksum}" >&2
            exit 1
          fi
          echo "updating ${new_checksums_path} with new checksum" >&2
          echo "${actual_checksum} ${lang_dir}" >> "$new_checksums_path"
        fi
        firefox_langdir="firefox/$(dirname "$tarpath")"
        mkdir -p "$firefox_langdir"
        tar -C "$firefox_langdir" --strip-components=1 -Jx -f "$tarfile" \
          || exit 1
        ln -fns /etc/firefox/distribution "${firefox_langdir}/distribution"
        ln -fns /etc/firefox/syspref.js \
                "${firefox_langdir}/defaults/pref/syspref.js"
        cat <<'FF_PUAVO_JS_EOF' > "${firefox_langdir}/firefox-puavodesktop.js"
// 

lockPref("autoadmin.global_config_url", "file:///etc/firefox/puavodesktop.js");
FF_PUAVO_JS_EOF
      done < "$firefox_checksums_path"

      # hard link many duplicate files
      rdfind -makehardlinks true firefox/*

      # Set LC_COLLATE=C so that files always sort in the same
      # way (so we get the same tar-archive independent of locales).
      env LC_COLLATE=C \
        tar -C firefox -j --mtime='2000-01-01 00:00:00 +00:00' --sort=name -c \
          -f "$upstream_pack" .
    )
    ;;
  *)
    ;;
esac
