#!/usr/bin/env sh
set -x

CONTENTS_ROOT="/Applications/Google Drive.app/Contents"
RESOURCES_ROOT="$CONTENTS_ROOT/Resources"
BINARIES_ROOT="$CONTENTS_ROOT/MacOS"
LOAD_DFSFUSE="$BINARIES_ROOT/load_dfsfuse"
MOUNT_DFSFUSE="$BINARIES_ROOT/mount_dfsfuse"
MOUNT_HELPER="$BINARIES_ROOT/mount_helper"

# Must be called after cleanup and before starting the new application.
setuid() {
  if [[ -O "$BINARIES_ROOT" ]]; then  # Directory is owned by this user (root)
    # setuid the load_dfsfuse, mount_dfsfuse, and mount_helper binaries.
    chmod u+s "$LOAD_DFSFUSE"
    chmod u+s "$MOUNT_DFSFUSE"
    chmod u+s "$MOUNT_HELPER"
  else
    exit 1
  fi
}

update_quicklookd() {
  /usr/bin/qlmanage -r
}

cleanup_old_app() {
  if [[ -e "/Applications/Google Drive File Stream.app/Contents/MacOS/Google Drive" ]]; then
    if [[ -d "/Applications/Google Drive.app" ]]; then

      # Somehow ended up with two applications, delete the old one.
      rm -rf "/Applications/Google Drive File Stream.app"
    else

      # The binary got updated but the application name did not. Rename the app.
      mv "/Applications/Google Drive File Stream.app" "/Applications/Google Drive.app"
    fi
  else
    if [[ -d "/Applications/Google Drive.app" ]]; then
      # New app got installed, delete the old one.
      rm -rf "/Applications/Google Drive File Stream.app"
    fi
    # Otherwise, new app did not get installed nor did old app get updated. Do
    # nothing in this case.
  fi
}

unload_old_kext() {
  kextunload -b com.google.dfsfuse.filesystems.dfsfuse -q || true
}

pgrep 'Google Drive File Stream'
if [ $? -eq 0 ]; then
  # Figure out user running the old application.
  LOCAL_USER=$( ps aux | grep 'Google Drive File Stream' | grep -v grep | awk '{ print $1; }' | head -n1 )
  # Tell the old application to quit by sending a SIGTERM to the
  # 'Google Drive File Stream' child process.
  pkill -TERM 'Google Drive File Stream'

  # Give the old application up to 30s to quit.
  for i in $( seq 30 ); do
    PID=$( pgrep 'Google Drive File Stream' )
    if [[ -z "$PID" ]]; then
      break
    fi
    sleep 1
  done

  # Forcibly kill the old application in case it is still lingering around.
  # Note that GoogleDriveFS has a SIGTERM handler which we bypass below by
  # sending a KILL signal.
  pkill -9 'Google Drive File Stream' || true
  pkill -9 FinderSyncExtension || true

  # Note that signal handlers invoked after sending the signals above are
  # processed asynchronously.
  sleep 2

  cleanup_old_app
  update_quicklookd
  unload_old_kext
  setuid

  # Open new app as the user running the old application.
  su -l "${LOCAL_USER}" -c 'open "/Applications/Google Drive.app"'

  # The only way to make Finder work well with the extension after renaming the
  # app appears to be by restarting Finder.
  killall Finder
else
  # Check if a keystone ticket exists. Note that currently the keystone ticket
  # for com.google.drivefs is not deleted upon uninstalling the application.
  /Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/MacOS/ksadmin --print \
    --productid com.google.drivefs
  EXIT_CODE=$?

  cleanup_old_app
  update_quicklookd
  setuid

  # Ask any existing Google Drive processes to restart themselves.
  # TODO(pliard): Change this back to killing all the Google Drive File Stream
  # processes in the field.

  pkill -USR1 -nx 'Google Drive'

  unload_old_kext

  # COMMAND_LINE_INSTALL environment variable is set when Google Drive is
  # installed or upgraded from the command line (via the `installer` program);
  # In this case, and if this is a new installation, don't auto-start the app.
  if [[ -z "$COMMAND_LINE_INSTALL" && ${EXIT_CODE} -ne 0 ]]; then
    open "/Applications/Google Drive.app"
  fi
fi

TAG="$KS_TICKET_AP"
if [ -z "$TAG" ]; then
  TAG=$(/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/MacOS/ksadmin --print-tag \
        --productid com.google.drivefs)
fi

if [[ "$TAG" = "canary" ]]; then
  canary=1
else
  canary=0
fi

# Register with Keystone.
/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/MacOS/ksadmin --register \
  --productid com.google.drivefs \
  --version 74.0.3.0 \
  --xcpath "/Applications/Google Drive.app" \
  --url https://tools.google.com/service/update2

mkdir -p "/Library/Application Support/Google/DriveFS"
echo $canary > "/Library/Application Support/Google/DriveFS/cv"

exit 0
