#!/usr/bin/env bash

#----------------------- installing client --------------------
copy_client() {
  target="$1"
  echo "Copying client files to $target"

  mkdir "$target"
  mkdir "$target/data"
  mkdir "$target/data/logs"
  mkdir "$target/data/config"

  cp -r client/* "$target"
  cp silver "${target}/pc-print-client-service"
  chmod +x "${target}/pc-print-client-service"
  cp updater "${target}/pc-print-client-updater"
  chmod +x "${target}/pc-print-client-updater"
}

install_queue() {
  target="$1"
  echo "Installing PaperCut Printer"
  PRINTER_ID="PAPERCUT_POCKET_PRINTER"
  PRINTER_NAME="PaperCut Printer"
  "${target}/pc-print-client-service" command install-queue -printerId="PAPERCUT_POCKET_PRINTER" -printerName="PaperCut Printer"
}

install_client_service() {
  target="$1"
  echo "Installing print client service"
  "${target}/pc-print-client-service" install

  "${target}/pc-print-client-service" start
}

bulk_link_client() {
  local region="$1"
  local orgId="$2"
  local target="$3"
  echo "bulk link command params: -region=$region -orgId=$orgId"
 "${target}/pc-print-client-service" command bulk-link --region "${region}" --orgId "${orgId}"
}

install_client() {
  local region="$1"
  local orgId="$2"
  local target="$3"

  cleanup_existing_service "${target}"
  copy_client "${target}"
  bulk_link_client "${region}" "${orgId}" "${target}"
  install_client_service "${target}"
}

cleanup_existing_service(){
    target="$1"
    #
    # If it's an install-over-the top, uninstall the service first
    # Note: uninstalling and stopping pc-print-client-service won't uninstall the edge node,
    # it will tell silver to unregister itself as a user service
    #
    if [[ -f "${target}/pc-print-client-service" ]]; then
        echo "pc-print-client service already exists. Uninstalling..."
        # shellcheck disable=SC1046
        if "${target}/pc-print-client-service" stop; then
          echo "stopped pc-print-client service successfully"
        else
          echo "stopping pc-print-client service failed with code $?"
        fi

        if "${target}/pc-print-client-service" uninstall; then
          echo "uninstalled pc-print-client service successfully"
        else
          echo "uninstall of pc-print-client service failed with code $?"
        fi
    fi
}
# ----------------------- installing edgenode ---------------------------------
copy_en() {
  target="$1"
  echo "Copying edgenode files to $target"

  mkdir "$target"
  mkdir "$target/data"
  mkdir "$target/data/logs"
  mkdir "$target/data/config"

  cp -r edgenode/* "$target"
  cp silver "${target}/pc-edgenode-service"
  chmod +x "${target}/pc-edgenode-service"
  cp updater "${target}/pc-edgenode-updater"
  chmod +x "${target}/pc-edgenode-updater"

  "${target}/pc-edgenode-service" command split-edgenode
}

link_en() {
  target="$1"
  system_key="$2"
  local region="$3"
  echo "linking edgenode"
  "${target}/pc-edgenode-service" command link --bulklink --region "$region" --systemKey "$system_key" --appVersion="2026-05-28-0159" --edgenodeUpdaterPath="./pc-edgenode-updater"
}

install_en_service() {
  target="$1"
  echo "Installing edgenode service"
  "${target}/pc-edgenode-service" install
  echo "installing DPM"
  "${target}/pc-edgenode-service" command install-dpm
  # This is a workaround for in case Gatekeeper puts the files into quarantine. Although files are signed and notarized,
  # It was still quarantined because of how it was installed
  # Gatekeeper shows the popup because quarantine exists
  # Removing quarantine removes the popup
  # TODO: proper investigation can be done to understand the root cause when have time/capacity
  xattr -dr com.apple.quarantine /usr/libexec/cups/backend/papercut
  xattr -dr com.apple.quarantine /usr/libexec/cups/filter/papercut

  echo "Starting edgenode service"
  "${target}/pc-edgenode-service" start
}

install_en() {
  echo "running install_en as $(whoami)"
  system_key=$1
  local region=$2
  target="/Library/PaperCut Hive"
  #
  # If it's an install-over-the top, uninstall the service first
  # Note: uninstalling and stopping pc-edgenode-service won't uninstall the edge node,
  # it will tell silver to unregister itself as a system service
  #
  if [[ -f "${target}/pc-edgenode-service" ]]; then
      echo "pc-edgenode-service already exists from the previous installation. Uninstalling edge node..."
      if "${target}/pc-edgenode-service" stop; then
        echo "stopped pc-edgenode-service successfully"
      else
        echo
      fi
      if "${target}/pc-edgenode-service" uninstall; then
        echo "uninstalled pc-edgenode-service successfully"
      else
        echo "uninstall of pc-edgenode-service service failed with code $?"
      fi
  fi
  copy_en "${target}"
  link_en "${target}" "${system_key}" "${region}"
  install_en_service "${target}"
}

update_user_in_uninstall() {
  echo "update_user_in_uninstall as $(whoami)"
  user_name=$1
  uninstall_file="/Library/PaperCut Hive/Uninstall.command"
  cat Uninstall.command \
      | sed "s|@user_name@|"${user_name}"|g" \
      > "${uninstall_file}"
  chmod +x "${uninstall_file}"
}

# -----------------------------------------------------------------
echo "Running installer script with args: $1 $2 $3 $4"
region=$2
orgId=$3

# Detect current console (logged-in) user
current_user=$(stat -f%Su /dev/console)
if [[ -z "${current_user}" ]]; then
  echo "Error: Could not determine the logged-in user." >&2
  exit 1
fi
current_user_home=$(dscl . -read /Users/"${current_user}" NFSHomeDirectory | cut -d' ' -f2)
current_dir="$(pwd)"

echo "Detected current user: ${current_user}"
echo "Current directory: ${current_dir}"
case "$1" in
  install_client)
    target=$4
    install_client "${region}" "${orgId}" "${target}"
    ;;
  *)
    system_key=$1
    install_en "${system_key}" "${region}"

    # --- Smart chown logic ---
    # Only chown if current dir is not already owned by the user
    dir_owner=$(stat -f%Su "${current_dir}")
    if [[ "${dir_owner}" != "${current_user}" ]]; then
        echo "Changing ownership of current directory to ${current_user}"
        chown -R "${current_user}" "${current_dir}"
    else
        echo "Ownership already correct (${current_user}), skipping chown."
    fi

    echo "Installing client component as ${current_user}..."
    target="${current_user_home}/Library/PaperCut Hive"
    su - "${current_user}" -c "(cd \"${current_dir}\" && \"${0}\" install_client \"${region}\" \"${orgId}\" \"${target}\")"

    # Important: run install_queue after install_client:bulk-link not before, otherwise there will be permission issues with
    # accessing ${current_user_home}/Library/PaperCut Hive/data/config/cloud-region.conf
    echo "Installing PaperCut Printer queue as $(whoami)..."
    install_queue "${target}"

    echo "Updating uninstall script..."
    update_user_in_uninstall "$current_user"
    ;;
esac
