#!/bin/sh

set -eu

command=$1
shift

add_desktop_file_fixer() {
  cat <<'EOF' > /etc/X11/Xsession.d/70fix-chrome-desktop-files
# Change all google-chrome .desktop files to run through
# /usr/bin/google-chrome instead of the (changing) puavo-pkg path.
if [ -d ~/.local/share/applications ]; then
  find ~/.local/share/applications/ -name '*.desktop' -print0 \
    | xargs -0 --no-run-if-empty \
            sed -i '/^Exec=.*google-chrome /s/^Exec=.*\/google-chrome /Exec=\/usr\/bin\/google-chrome-stable /'
fi
EOF
}

write_startup_wrapper() {
  cat <<'EOF' > /usr/bin/google-chrome-stable.tmp
#!/bin/sh

set -eu

browser_dir=~/.config/google-chrome
browser_name='Google Chrome'

# workaround bug https://issues.chromium.org/issues/40936572
apply_sso_workaround() {
  local_state_path="${browser_dir}/Local State"
  if [ -e "$local_state_path" ]; then
    # "Local State" exists, we're too late and will not bother
    return 0
  fi

  jq --null-input '.net.received_http_auth_negotiate_headers = true' \
    > "${local_state_path}.tmp" || return 1
  mv "${local_state_path}.tmp" "$local_state_path" || return 1
}

browser_is_active() {
  # This checks browser activity on any host sharing the home directory.
  # If there are files in the browser directory which are modified
  # in the last minute, there must be an active session on some host.
  local browser_dir

  browser_dir=$1
  find "$browser_dir" -printf '%Ts\n' \
    | awk '
        BEGIN {
          current_time = strftime("%s")
          is_active = 1
        }
        # consider that browser is active (on some host), in case there is
        # any file that were modified in the last minute (but ignore files
        # that are were modified later than a minute in the future)
        ((current_time - 60) <= $1) && ($1 <= (current_time + 60)) { is_active = 0 }
        END { exit(is_active) }
      '
}

fix_browser_lock() {
  local browser_lock browser_lock_hostname puavo_hostname

  browser_lock=$(readlink "${browser_dir}/SingletonLock" 2>/dev/null) || true

  if [ -z "$browser_lock" ]; then
    # no lock, okay
    return 0
  fi

  browser_lock_hostname=${browser_lock%-*}

  read puavo_hostname < /etc/puavo/hostname || return 1

  if [ "$puavo_hostname" = "$browser_lock_hostname" ]; then
    # lock is for the same host, okay
    return 0
  fi

  if browser_is_active "$browser_dir"; then
    zenity --error --title="${browser_name} startup error" --timeout=10 \
           --no-wrap --text="${browser_name} is active on host ${browser_lock_hostname}, please close it there and then try again" || true
    return 1
  fi

  rm -f "$browser_dir"/Singleton* || return 1

  return 0
}

browser_running() {
  # this checks browser activity on this host
  pgrep -x -U "$USER" chrome >/dev/null
}

manage_preferences() {
  tmpfile="${preferences_file}.tmp"

  if [ -e "$preferences_file" ]; then
    jq "$@" "$preferences_file" > "$tmpfile" || return 1
  else
    jq --null-input "$@" > "$tmpfile" || return 1
  fi

  mv "$tmpfile" "$preferences_file"
}

set_first_homepage() {
  first_homepage=$1

  manage_preferences --arg first_homepage "$first_homepage" '
    .browser.show_home_button = true
    | .homepage = $first_homepage
    | .homepage_is_newtabpage = false
    | .session.restore_on_startup = 4
    | .session.startup_urls = [ $first_homepage ]
  '
}

default_args="--disable-infobars --disable-search-engine-choice-screen --no-default-browser-check --no-first-run"
extra_args=$(puavo-conf puavo.www.chromium.extra_args 2>/dev/null) || true

if ! fix_browser_lock; then
  exit 1
fi

if ! browser_running; then
  preferences_dir=~/.config/google-chrome/Default
  preferences_file="${preferences_dir}/Preferences"

  mkdir -p "$preferences_dir"

  first_homepage=$( echo "$HOMEPAGE" | awk -F '|' '{ print $1 }')
  second_homepage=$(echo "$HOMEPAGE" | awk -F '|' '{ print $2 }')

  if [ -n "$first_homepage" ]; then
    if set_first_homepage "$first_homepage"; then
      if [ -n "$second_homepage" ]; then
        manage_preferences --arg second_homepage "$second_homepage" '
          .session.startup_urls += [ $second_homepage ]
        ' || true
      fi
    fi
  fi

  manage_preferences '.browser.custom_chrome_frame = false' || true

  apply_sso_workaround || true
fi

exec /usr/bin/google-chrome-stable.puavopkg $default_args \
       --simulate-outdated-no-au='Thu, 31 Dec 2099 23:59:59 GMT' \
       $extra_args "$@"
EOF
  chmod 755 /usr/bin/google-chrome-stable.tmp
  mv /usr/bin/google-chrome-stable.tmp /usr/bin/google-chrome-stable
}

case "$command" in
  configure)
    upstream_dir=$1

    mkdir -p /usr/bin                              \
             /usr/share/applications               \
             /usr/share/man/man1                   \
             /usr/share/icons/hicolor/16x16/apps   \
             /usr/share/icons/hicolor/22x22/apps   \
             /usr/share/icons/hicolor/24x24/apps   \
             /usr/share/icons/hicolor/32x32/apps   \
             /usr/share/icons/hicolor/48x48/apps   \
             /usr/share/icons/hicolor/64x64/apps   \
             /usr/share/icons/hicolor/128x128/apps \
             /usr/share/icons/hicolor/256x256/apps

    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_16.png" \
            /usr/share/icons/hicolor/16x16/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_22.png" \
            /usr/share/icons/hicolor/22x22/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_24.png" \
            /usr/share/icons/hicolor/24x24/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_32.png" \
            /usr/share/icons/hicolor/32x32/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_48.png" \
            /usr/share/icons/hicolor/48x48/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_64.png" \
            /usr/share/icons/hicolor/64x64/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_128.png" \
            /usr/share/icons/hicolor/128x128/apps/google-chrome.png
    ln -fns "${upstream_dir}/opt/google/chrome/product_logo_256.png" \
            /usr/share/icons/hicolor/256x256/apps/google-chrome.png
    ln -fns "${upstream_dir}/usr/share/man/man1/google-chrome.1" \
            /usr/share/man/man1/google-chrome.1

    ln -fns "${upstream_dir}/opt/google/chrome/google-chrome" \
            /usr/bin/google-chrome-stable.puavopkg
    write_startup_wrapper
    add_desktop_file_fixer

    sed '/^MimeType=/a\
StartupNotify=true' "${upstream_dir}/usr/share/applications/google-chrome.desktop" \
      > /usr/share/applications/google-chrome.desktop
    ;;

  unconfigure)
    if pgrep -f '/opt/google/chrome/chrome' > /dev/null 2>&1; then
      echo 'Google Chrome is running, will not unconfigure' >&2
      # 4 == application is busy
      exit 4
    fi
    rm -f /etc/X11/Xsession.d/70fix-chrome-desktop-files          \
          /usr/bin/google-chrome-stable                           \
          /usr/bin/google-chrome-stable.puavopkg                  \
          /usr/share/applications/google-chrome.desktop           \
          /usr/share/icons/hicolor/16x16/apps/google-chrome.png   \
          /usr/share/icons/hicolor/22x22/apps/google-chrome.png   \
          /usr/share/icons/hicolor/24x24/apps/google-chrome.png   \
          /usr/share/icons/hicolor/32x32/apps/google-chrome.png   \
          /usr/share/icons/hicolor/48x48/apps/google-chrome.png   \
          /usr/share/icons/hicolor/64x64/apps/google-chrome.png   \
          /usr/share/icons/hicolor/128x128/apps/google-chrome.png \
          /usr/share/icons/hicolor/256x256/apps/google-chrome.png \
          /usr/share/man/man1/google-chrome.1
    ;;

  unpack)
    upstream_pack=$1
    upstream_dir=$2
    dpkg -x "$upstream_pack" "$upstream_dir"
    chmod 0755 "$upstream_dir"
    ;;

  *)
    ;;
esac
