#!/bin/bash
# (C) Wiz, Inc. 2023-present
# All rights reserved
# Licensed for Wiz customers only under the Wiz Master Subscription Agreement or such other agreement in place between Wiz and customer
# Wiz Sensor installation script: install and set up the Sensor on supported Linux distributions
# using the package manager and Wiz repositories.
#
# Custom package repository (e.g. a customer-mirrored APT/RPM repo), configured per variant:
#   SENSOR_APT_URL / SENSOR_YUM_URL          base URL of the mirror
#   SENSOR_APT_KEY_URL / SENSOR_YUM_KEY_URL  GPG key URL for the mirror
#   SENSOR_APT_CHANNEL / SENSOR_YUM_CHANNEL  suite name (set to "none" for a flat/root repo)
#   WIZ_ENABLE_APT_GPGCHECK / WIZ_ENABLE_YUM_GPGCHECK  toggle signature checks
#   PACKAGE_PUBLIC_KEY_FILE                  local GPG key file (applies to both; forces gpg on)
# A custom apt URL with gpgcheck disabled is trusted directly (deb [trusted=yes]).

BOLD="$(tput bold 2> /dev/null || printf '')"
RED="$(tput setaf 1 2> /dev/null || printf '')"
GREEN="$(tput setaf 2 2> /dev/null || printf '')"
BLUE="$(tput setaf 4 2> /dev/null || printf '')"
YELLOW="$(tput setaf 3 2> /dev/null || printf '')"
NO_COLOR="$(tput sgr0 2> /dev/null || printf '')"

info() {
  printf '%s\n' "${BOLD}${BLUE}$*${NO_COLOR}"
}

warn() {
  printf '%s\n' "${YELLOW}$*${NO_COLOR}"
}

error() {
  printf '%s\n' "${RED}$*${NO_COLOR}" >&2
}

completed() {
  printf '%s\n' "${GREEN}$*${NO_COLOR}"
}

# Package repository file this run created, if any. A failed install must not
# leave it behind: an unreachable repo makes every later system-wide package
# manager update fail, not just ours.
ADDED_REPO_FILE=""

# Only track files we create, so a failed re-install doesn't delete a repository
# that was already configured and working on this host.
track_added_repo_file() {
  [ -f "$1" ] || ADDED_REPO_FILE="$1"
}

on_exit() {
  status=$?
  if [ -n "$npipe" ]; then
    rm -f "$npipe"
  fi
  if [ "$status" -ne 0 ] && [ -n "$ADDED_REPO_FILE" ]; then
    rm -f "$ADDED_REPO_FILE"
  fi
  # script exits after this
}

set_consts() {
  DOCKER_ONLY_OS_LIST="GCOS Flatcar ClearLinux Photon Gentoo"
}

is_truthy() {
  case "$1" in
    1 | [tT] | [tT][rR][uU][eE] | [yY] | [yY][eE][sS] | [oO][nN]) return 0 ;;
    *) return 1 ;;
  esac
}

is_env_enabled() {
  case "$1" in
    1 | [tT][rR][uU][eE]) return 0 ;;
    *) return 1 ;;
  esac
}

is_semver() {
  version=$1
  SEMVER_REGEX="^[0-9]+\.[0-9]+\.[0-9]+$"
  if [[ $version =~ $SEMVER_REGEX ]]; then
    return 0
  else
    return 1
  fi
}

get_sensor_package_version() {
  # No need to get the version mapping if we are installing the latest version
  if [ "$WIZ_SENSOR_VERSION" = "" ]; then
    return
  fi

  # Custom mirror can't reach the mapping file; version is an exact one (config validates)
  if [ -n "$REPO_URL_OVERRIDDEN" ]; then
    echo "$WIZ_SENSOR_VERSION"
    return
  fi

  version=$(curl_proxy "$SENSOR_VERSION_MAPPING_URL" | grep "^$WIZ_SENSOR_VERSION:" | sed "s/$WIZ_SENSOR_VERSION: //")
  if [ "$version" = "" ]; then
    # If this is not a tag, assume it's the real version name to use
    echo "$WIZ_SENSOR_VERSION"
  fi
  echo "$version"
}

config() {
  if [ "${WIZ_PRIVILEGED_INSTALL,,}" == "true" ] && [ "$CONTAINER_INSTALL" != "1" ]; then
    error "WIZ_PRIVILEGED_INSTALL is only supported for container-based installations (Docker, Containerd or Podman)."
    exit 1
  fi

  if [ "${WIZ_HOST_NETWORK,,}" == "true" ] && [ "$CONTAINER_INSTALL" != "1" ]; then
    error "WIZ_HOST_NETWORK is only supported for container-based installations (Docker, Containerd or Podman)."
    exit 1
  fi

  if [ "${WIZ_HOST_NETWORK,,}" == "true" ] && [ -n "$WIZ_METRICS_PORT" ]; then
    error "WIZ_HOST_NETWORK and WIZ_METRICS_PORT are incompatible. Port publishing is not supported in host network mode."
    exit 1
  fi

  if is_truthy "$WIZ_PACKAGE_SKIP_INSTALL" && [ "$CONTAINER_INSTALL" = "1" ]; then
    error "WIZ_PACKAGE_SKIP_INSTALL is only supported for package-based installations."
    exit 1
  fi

  if is_truthy "$WIZ_PACKAGE_SKIP_INSTALL" && [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    error "WIZ_PACKAGE_SKIP_INSTALL and WIZ_INSTALL_ONLY are mutually exclusive."
    exit 1
  fi

  if is_truthy "$WIZ_PACKAGE_INSTALL_ONLY" && [ "$CONTAINER_INSTALL" = "1" ]; then
    error "WIZ_PACKAGE_INSTALL_ONLY is only supported for package-based installations."
    exit 1
  fi

  if is_truthy "$WIZ_PACKAGE_INSTALL_ONLY" && is_truthy "$WIZ_PACKAGE_SKIP_INSTALL"; then
    error "WIZ_PACKAGE_INSTALL_ONLY and WIZ_PACKAGE_SKIP_INSTALL are mutually exclusive."
    exit 1
  fi

  if [ -n "$WIZ_DIR" ] && [ "$CONTAINER_INSTALL" != "1" ]; then
    error "WIZ_DIR is only supported for container-based installations (Docker, Containerd or Podman)."
    exit 1
  elif [ -z "$WIZ_DIR" ]; then
    if [ "$OS" = "GCOS" ]; then
      WIZ_DIR=/var/lib/wiz
    else
      WIZ_DIR=/opt/wiz
    fi
  fi

  WIZ_DOMAIN="wiz.io"
  WIZ_BACKEND_ENV="${WIZ_BACKEND_ENV:-$WIZ_ENV}"
  WIZ_BACKEND_ENV="${WIZ_BACKEND_ENV,,}"
  WIZ_SENSOR_PRIVATELINK="${WIZ_SENSOR_PRIVATELINK:-$SENSOR_PRIVATELINK}"
  DEFAULT_DISK_SCANNER_REPOSITORY="wiz-app/wiz-workload-scanner"

  # support federal variants
  if [[ "$WIZ_BACKEND_ENV" =~ ^(fedtest|fedstg1|fedint|fedinttest|fedtestmil)$ ]]; then
    WIZ_DOMAIN="fedstg1.wiz.io"
    REPO_POSTFIX="-fedout"
    CONTAINER_REGISTRY="${CONTAINER_REGISTRY:-wizfedramp.azurecr.us}"
    DEFAULT_DISK_SCANNER_REPOSITORY="wiz-app/wiz-workload-scanner-fips"
  elif [[ "$WIZ_BACKEND_ENV" =~ ^(fedstg2|fedramp|fedstg2mil|milprod-mo|milprod)$ ]]; then
    WIZ_DOMAIN="wiz.us"
    REPO_POSTFIX="-fedramp"
    CONTAINER_REGISTRY="${CONTAINER_REGISTRY:-wizfedramp.azurecr.us}"
    DEFAULT_DISK_SCANNER_REPOSITORY="wiz-app/wiz-workload-scanner-fips"
  fi

  SENSOR_DIR=${WIZ_DIR}/sensor
  SENSOR_HOST_STORE=${SENSOR_DIR}/host-store
  SENSOR_ENV_FILE=${SENSOR_HOST_STORE}/engine.env
  SENSOR_LEGACY_CONFIG_FILE=${SENSOR_HOST_STORE}/config.yaml
  LOGFILE=${SENSOR_HOST_STORE}/install.log

  YUM_GPGCHECK=1
  if [[ -z "$WIZ_ENABLE_YUM_GPGCHECK" || "$WIZ_ENABLE_YUM_GPGCHECK" == "0" || "${WIZ_ENABLE_YUM_GPGCHECK,,}" == "false" ]]; then
    YUM_GPGCHECK=0
  fi

  APT_GPGCHECK=0
  if [[ "$WIZ_ENABLE_APT_GPGCHECK" == "1" || "${WIZ_ENABLE_APT_GPGCHECK,,}" == "true" ]]; then
    APT_GPGCHECK=1
  fi

  PACKAGE_PUBLIC_KEY_URL="https://downloads.${WIZ_DOMAIN}/sensor/sensor_public_key.asc"
  if [[ -n "$PACKAGE_PUBLIC_KEY_FILE" ]]; then
    if [ ! -f "$PACKAGE_PUBLIC_KEY_FILE" ]; then
      error "Public key file not found: $PACKAGE_PUBLIC_KEY_FILE"
      exit 1
    fi
    YUM_GPGCHECK=1
    APT_GPGCHECK=1
    PACKAGE_PUBLIC_KEY_URL="file://$PACKAGE_PUBLIC_KEY_FILE"
  fi

  # A mirror override for this OS's package manager means the Wiz version-mapping file
  # is unreachable, so the version must be exact. Package installs only; containers use the image tag.
  if [ "$CONTAINER_INSTALL" != "1" ]; then
    if { [ "$OS" = "Debian" ] && [ -n "$SENSOR_APT_URL" ]; } \
      || { [ "$OS" != "Debian" ] && [ -n "$SENSOR_YUM_URL" ]; }; then
      REPO_URL_OVERRIDDEN=1
    fi
  fi
  # gpgcheck on a custom mirror without a key would silently fetch the Wiz key (unreachable in air-gap)
  if [ -n "$REPO_URL_OVERRIDDEN" ] && [ -z "$PACKAGE_PUBLIC_KEY_FILE" ]; then
    if [ "$OS" = "Debian" ] && [ "$APT_GPGCHECK" = "1" ] && [ -z "$SENSOR_APT_KEY_URL" ]; then
      error "A custom SENSOR_APT_URL with apt gpgcheck enabled requires SENSOR_APT_KEY_URL or PACKAGE_PUBLIC_KEY_FILE."
      exit 1
    fi
    if [ "$OS" != "Debian" ] && [ "$YUM_GPGCHECK" = "1" ] && [ -z "$SENSOR_YUM_KEY_URL" ]; then
      error "A custom SENSOR_YUM_URL with yum gpgcheck enabled requires SENSOR_YUM_KEY_URL or PACKAGE_PUBLIC_KEY_FILE."
      exit 1
    fi
  fi

  SENSOR_VERSION_MAPPING_URL="https://downloads.${WIZ_DOMAIN}/sensor/sensor_linux_version_mapping.yaml"
  SENSOR_YUM_URL="${SENSOR_YUM_URL:-https://rpm.${WIZ_DOMAIN}/projects/sensor-repos${REPO_POSTFIX}}"
  SENSOR_YUM_KEY_URL="${SENSOR_YUM_KEY_URL:-$PACKAGE_PUBLIC_KEY_URL}"
  SENSOR_YUM_CHANNEL="${SENSOR_YUM_CHANNEL:-${YUM_CHANNEL:-sensor-yum}}"
  SENSOR_APT_URL="${SENSOR_APT_URL:-https://dpkg.${WIZ_DOMAIN}/projects/sensor-repos${REPO_POSTFIX}}"
  # A custom mirror can use a local key; the default Wiz repo metadata needs the Wiz repo signing key
  DEFAULT_APT_KEY_URL="https://dpkg.${WIZ_DOMAIN}/doc/repo-signing-key.gpg"
  if [[ -n "$REPO_URL_OVERRIDDEN" && -n "$PACKAGE_PUBLIC_KEY_FILE" ]]; then
    DEFAULT_APT_KEY_URL="$PACKAGE_PUBLIC_KEY_URL"
  fi
  SENSOR_APT_KEY_URL="${SENSOR_APT_KEY_URL:-$DEFAULT_APT_KEY_URL}"
  SENSOR_APT_CHANNEL="${SENSOR_APT_CHANNEL:-${APT_CHANNEL:-sensor-apt}}"

  # Build repo locations; the "none" channel sentinel means a flat (root) repo layout
  if [ "$SENSOR_YUM_CHANNEL" != "none" ]; then
    SENSOR_YUM_BASEURL="${SENSOR_YUM_URL%/}/${SENSOR_YUM_CHANNEL}"
  else
    SENSOR_YUM_BASEURL="${SENSOR_YUM_URL%/}/"
  fi
  if [ "$SENSOR_APT_CHANNEL" != "none" ]; then
    SENSOR_APT_REPO_SPEC="${SENSOR_APT_URL%/}/ ${SENSOR_APT_CHANNEL} main"
  else
    SENSOR_APT_REPO_SPEC="${SENSOR_APT_URL%/}/ ./"
  fi

  # Unsigned mirror: a custom apt URL with gpg disabled → trust the repo, skip key import
  APT_REPO_UNSIGNED=0
  if [ -n "$REPO_URL_OVERRIDDEN" ] && [ "$APT_GPGCHECK" = "0" ]; then
    APT_REPO_UNSIGNED=1
  fi
  YUM_GPGKEY_LINE="gpgkey=${SENSOR_YUM_KEY_URL}"
  if [ -n "$REPO_URL_OVERRIDDEN" ] && [ "$YUM_GPGCHECK" = "0" ]; then
    YUM_GPGKEY_LINE=""
  fi
  CONTAINER_REGISTRY_LOGIN="${CONTAINER_REGISTRY_LOGIN:-1}"
  CONTAINER_REGISTRY="${CONTAINER_REGISTRY:-wizio.azurecr.io}"
  DISK_SCANNER_DIR=${WIZ_DIR}/disk-scanner
  DISK_SCANNER_HOST_STORE=${DISK_SCANNER_DIR}/host-store
  TMP_DIR="${TMP_DIR:-/tmp}"
  export WIZ_DISK_SCANNER=${WIZ_DISK_SCANNER:-$WIZ_ENABLE_DISK_SCANNER}
  if [ "$WIZ_DISK_SCANNER" = "1" ] && [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    error "WIZ_DISK_SCANNER is not supported on sysvinit systems."
    exit 1
  fi
  export WIZ_BACKEND_ENV="${WIZ_BACKEND_ENV:-prod}"
  export WIZ_SENSOR_PRIVATELINK="${WIZ_SENSOR_PRIVATELINK:-false}"
  export WIZ_DISK_SCANNER_CPU_LIMIT=${WIZ_DISK_SCANNER_CPU_LIMIT:-0.2}
  export WIZ_DISK_SCANNER_MEMORY_LIMIT=${WIZ_DISK_SCANNER_MEMORY_LIMIT:-500m}
  export WIZ_DISK_SCANNER_VERSION="${WIZ_DISK_SCANNER_VERSION:-v1}"
  export WIZ_DISK_SCANNER_REPOSITORY="${WIZ_DISK_SCANNER_REPOSITORY:-$DEFAULT_DISK_SCANNER_REPOSITORY}"
  SENSOR_REPOSITORY="${SENSOR_REPOSITORY:-sensor}"
  BASE64_ENCODED_ENVS=("CONFIG_OVERRIDES" "EXTRA_PII")

  # Required for internal devops processes
  # shellcheck disable=SC2269
  SCRIPT_VERSION=1.0.13286
  if [ -z "1.0.13286" ]; then
    SCRIPT_VERSION=1.0.0
  fi

  if [ "$SENSOR_VERSION_SAME_AS_SCRIPT_VERSION" = "1" ]; then
    export WIZ_SENSOR_VERSION="1.0.13286"
  fi

  # Checked after WIZ_SENSOR_VERSION is finalized: a custom mirror can't resolve tags
  if [ -n "$REPO_URL_OVERRIDDEN" ] && [ -n "$WIZ_SENSOR_VERSION" ] && ! is_semver "$WIZ_SENSOR_VERSION"; then
    error "WIZ_SENSOR_VERSION must be an exact version (e.g. 1.0.123) with a custom repo URL; version tags cannot be resolved against a custom mirror."
    exit 1
  fi
}

print_banner() {
  if [ -z "$NO_BANNER" ]; then
    cat << 'BANNER'
  __        ___       ____
  \ \      / (_)____ / ___|  ___ _ __  ___  ___  _ __
   \ \ /\ / /| |_  / \___ \ / _ \ '_ \/ __|/ _ \| '__|
    \ V  V / | |/ /   ___) |  __/ | | \__ \ (_) | |
     \_/\_/  |_/___| |____/ \___|_| |_|___/\___/|_|

BANNER
  fi
}

setup_logger() {
  npipe="${TMP_DIR}/$$.tmp"
  mknod "$npipe" p
  tee < "$npipe" "$LOGFILE" &
  exec 1>&-
  exec 1> "$npipe" 2>&1
}

create_sensor_dir() {
  # shellcheck disable=SC2174
  mkdir -m 700 -p "$WIZ_DIR" || {
    error "Failed to create directory $WIZ_DIR"
    exit 1
  }
  mkdir -p "$SENSOR_HOST_STORE" || {
    error "Failed to create directory $SENSOR_HOST_STORE"
    exit 1
  }
  if [ "$WIZ_DISK_SCANNER" = "1" ]; then
    # shellcheck disable=SC2174
    mkdir -m 700 -p "$DISK_SCANNER_HOST_STORE" || {
      error "Failed to create directory $DISK_SCANNER_HOST_STORE"
      exit 1
    }
    # The disk scanner container runs as 2202:2202, while the non-container install runs it as root
    if [ "$CONTAINER_INSTALL" = "1" ]; then
      chown 2202:2202 "$DISK_SCANNER_HOST_STORE" || {
        error "Failed to set ownership on $DISK_SCANNER_HOST_STORE"
        exit 1
      }
    fi
  fi
  chmod -R 700 "$WIZ_DIR" || {
    error "Failed to set permissions on $WIZ_DIR"
    exit 1
  }
}

generate_persistent_id() {
  if [ ! -f "$SENSOR_HOST_STORE/persistent_id.yml" ]; then
    if command -v uuidgen &> /dev/null; then
      uuid=$(uuidgen)
    elif [ -f /proc/sys/kernel/random/uuid ]; then
      uuid=$(cat /proc/sys/kernel/random/uuid)
    elif command -v tr &> /dev/null && command -v fold &> /dev/null && command -v head &> /dev/null; then
      hex_string=$(tr -dc 'a-f0-9' < /dev/urandom | fold -w 32 | head -n 1)
      uuid="${hex_string:0:8}-${hex_string:8:4}-${hex_string:12:4}-${hex_string:16:4}-${hex_string:20:12}"
    fi

    if [ -n "$uuid" ]; then
      echo "id: $uuid" > "$SENSOR_HOST_STORE/persistent_id.yml"
    fi
  fi

  if [ -f "$SENSOR_HOST_STORE/persistent_id.yml" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    cp -a "$SENSOR_HOST_STORE/persistent_id.yml" "$DISK_SCANNER_HOST_STORE/persistent_id.yml"
  fi
}

select_install_method() {
  if [ -z "$CONTAINERD_INSTALL" ] && [ -z "$DOCKER_INSTALL" ] && [ -z "$PODMAN_INSTALL" ]; then
    if [[ "$DOCKER_ONLY_OS_LIST" =~ $OS ]]; then
      DOCKER_INSTALL=1
    else
      DOCKER_INSTALL=0
    fi
  fi

  if [ "$CONTAINERD_INSTALL" = "1" ]; then
    info "Installing Wiz Sensor using Containerd (requires nerdctl or ctr)"
    export CONTAINER_INSTALL="1"
  elif [ "$DOCKER_INSTALL" = "1" ]; then
    info "Installing Wiz Sensor using Docker"
    export CONTAINER_INSTALL="1"
  elif [ "$PODMAN_INSTALL" = "1" ]; then
    info "Installing Wiz Sensor using Podman"
    export CONTAINER_INSTALL="1"
  elif [ -n "$LOCAL_PACKAGE" ]; then
    info "Installing Wiz Sensor using local package"
  else
    info "Installing Wiz Sensor using package manager"
  fi

  if [ "$WIZ_SENSOR_TYPE" = "workstation" ]; then
    info "Installing Wiz Sensor as a workstation sensor"
  fi

  if is_truthy "$WIZ_PACKAGE_SKIP_INSTALL"; then
    info "Configured to skip Wiz Sensor package installation"
  fi

  if is_truthy "$WIZ_PACKAGE_INSTALL_ONLY"; then
    info "Configured to install Wiz Sensor package only (no configuration, no service start)"
  fi
}

get_base_domain() {
  privatelink_prefix=""
  is_truthy "$WIZ_SENSOR_PRIVATELINK" && privatelink_prefix="privatelink."

  if [ "$WIZ_BACKEND_ENV" = "prod" ]; then
    echo "${privatelink_prefix}app.wiz.io"
  elif [ "$WIZ_BACKEND_ENV" = "fedramp" ]; then
    echo "${privatelink_prefix}app.wiz.us"
  elif [ "$WIZ_BACKEND_ENV" = "fedstg2" ]; then
    echo "${privatelink_prefix}fedstg2.wiz.us"
  elif [ "$WIZ_BACKEND_ENV" = "fedstg2mil" ]; then
    echo "${privatelink_prefix}app.wizfedstg2.mil"
  elif [ "$WIZ_BACKEND_ENV" = "milprod-mo" ]; then
    echo "${privatelink_prefix}app.wiz.mil"
  elif [ "$WIZ_BACKEND_ENV" = "milprod" ]; then
    echo "${privatelink_prefix}app.wiz-mil.us"
  else
    echo "${privatelink_prefix}$WIZ_BACKEND_ENV.wiz.io"
  fi
}

get_auth_subdomain() {
  echo "auth.$(get_base_domain)"
}

get_auth_url() {
  echo "https://$(get_auth_subdomain)/oauth/token"
}

# Wrapper around curl that always injects the configured proxy flags.
# All network calls in this script must go through curl_proxy, not plain curl,
# so that WIZ_HTTP_PROXY_URL and friends are honored in every code path.
curl_proxy() {
  local args=()
  if [ -n "$WIZ_HTTP_PROXY_URL" ]; then
    args+=(--proxy "$WIZ_HTTP_PROXY_URL")
  fi

  if [ -n "$WIZ_HTTP_PROXY_USERNAME" ] && [ -n "$WIZ_HTTP_PROXY_PASSWORD" ]; then
    args+=(--proxy-user "$WIZ_HTTP_PROXY_USERNAME:$WIZ_HTTP_PROXY_PASSWORD")
  fi

  if [ -n "$HTTP_PROXY_CERT_PATH" ]; then
    args+=(--cacert "$HTTP_PROXY_CERT_PATH")
  fi

  curl "${args[@]}" "$@"
}

check_api_key() {
  if [[ -z $WIZ_API_CLIENT_ID ]] || [[ -z $WIZ_API_CLIENT_SECRET ]]; then
    error "Missing API key. Please set WIZ_API_CLIENT_ID and WIZ_API_CLIENT_SECRET environment variables and try again."
    exit 1
  fi

  if [[ -n "$WIZ_EXTRA_SSL_CERT_DIR" ]]; then
    warn "Skipping API key check since WIZ_EXTRA_SSL_CERT_DIR is set."
    return 0
  fi

  if [[ -z $WIZ_SKIP_COMM_CHECK ]]; then
    local auth_url
    auth_url=$(get_auth_url)

    local http_status_code
    if ! http_status_code=$(curl_proxy -s --write-out "%{http_code}" --output /dev/null -X POST "$auth_url" \
      -A "wiz-sensor-install-script/1.0.13286" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      -H "encoding: UTF-8" \
      --data-urlencode "grant_type=client_credentials" \
      --data-urlencode "client_id=$WIZ_API_CLIENT_ID" \
      --data-urlencode "client_secret=$WIZ_API_CLIENT_SECRET" \
      --data-urlencode "audience=wiz-agent-api"); then
      error "Failed to connect to $auth_url"
      exit 1
    fi
    if [ "$http_status_code" -ne "200" ]; then
      error "Invalid API key."
      exit 1
    fi
  fi
}

check_databricks() {
  if [ "$WIZ_NOT_DATABRICKS" = "1" ]; then
    return
  fi

  if [ -d "/databricks" ]; then
    error "Databricks environments are not supported. If this is not a Databricks environment, set WIZ_NOT_DATABRICKS=1 to override."
    exit 1
  fi
}

check_arch() {
  arch=$(uname -m)
  if [ "$arch" != "x86_64" ] && [ "$arch" != "aarch64" ] && [ "$arch" != "s390x" ] && [ "$arch" != "ppc64le" ]; then
    error "Unsupported architecture: $arch"
    exit 1
  fi
}

check_kernel_version() {
  kernel_ver=$(uname -r | cut -d '-' -f 1)

  local required_major=4
  local required_minor=18
  if [ "$WIZ_DISABLE_RUNTIME_DETECTION" = "1" ]; then
    required_major=3
    required_minor=10
  fi

  if ! test_kernel_version "$required_major" "$required_minor"; then
    error "Unsupported kernel version: $kernel_ver (minimum: ${required_major}.${required_minor})"
    exit 1
  fi
}

# Prints the RedHat package manager: dnf if available, otherwise yum.
redhat_package_manager() {
  if command -v dnf &> /dev/null; then
    echo dnf
  else
    echo yum
  fi
}

ensure_curl_installed() {
  if command -v curl &> /dev/null; then
    return 0
  fi

  if is_truthy "$SENSOR_SKIP_INSTALL_CURL"; then
    error "curl is not installed and SENSOR_SKIP_INSTALL_CURL is set. Please install curl and re-run the script."
    exit 1
  fi

  info "curl is not installed; installing it via the system package manager"
  case "$OS" in
    Debian)
      apt-get update || warn "'apt-get update' failed; will try installing curl with the existing package index"
      apt-get install -y curl
      ;;
    RedHat)
      "$(redhat_package_manager)" install -y curl
      ;;
    SUSE)
      zypper --non-interactive install curl
      ;;
    Alpine)
      apk add --no-cache curl
      ;;
    Gentoo)
      emerge --quiet net-misc/curl
      ;;
    *)
      error "curl is not installed and this script does not know how to install it on $OS. Install curl manually and re-run, or set SENSOR_SKIP_INSTALL_CURL=1 after installing it."
      exit 1
      ;;
  esac

  if ! command -v curl &> /dev/null; then
    error "Failed to install curl. Install it manually and re-run the script."
    exit 1
  fi
}

test_kernel_version() {
  required_major=$1
  required_minor=$2

  kernel_ver=$(uname -r | cut -d '-' -f 1)
  current_major=$(echo "$kernel_ver" | cut -d '.' -f 1)
  current_minor=$(echo "$kernel_ver" | cut -d '.' -f 2)

  if [ "$current_major" -gt "$required_major" ]; then
    return 0
  elif [ "$current_major" -eq "$required_major" ] && [ "$current_minor" -ge "$required_minor" ]; then
    return 0
  else
    return 1
  fi
}

check_os_and_distro() {
  KNOWN_DISTRIBUTION="(Debian|Ubuntu|RedHat|CentOS|openSUSE|Amazon|Arista|SUSE|Rocky|AlmaLinux|Clear Linux OS|Container-Optimized OS|Flatcar Container Linux|Alpine|Gentoo|Devuan)"
  DISTRIBUTION=$(lsb_release -d 2> /dev/null | grep -Eo "$KNOWN_DISTRIBUTION" || grep -Eo "$KNOWN_DISTRIBUTION" /etc/issue 2> /dev/null || grep -Eo "$KNOWN_DISTRIBUTION" /etc/Eos-release 2> /dev/null || grep -m1 -Eo "$KNOWN_DISTRIBUTION" /etc/os-release 2> /dev/null || uname -s)
  SERVICE_MANAGER="systemd"

  # Devuan is Debian without systemd - detect before the generic Debian check
  # since /etc/debian_version exists on Devuan too. Pick the service manager
  # here rather than in the common flow so nothing outside the Devuan branch
  # is affected.
  if [ -f /etc/devuan_version ] || [ "$DISTRIBUTION" == "Devuan" ]; then
    OS="Debian"
    if has_systemd; then
      SERVICE_MANAGER="systemd"
    else
      SERVICE_MANAGER="sysvinit"
    fi
  elif [ -f /etc/debian_version ] || [ "$DISTRIBUTION" == "Debian" ] || [ "$DISTRIBUTION" == "Ubuntu" ]; then
    OS="Debian"
  elif [ -f /etc/redhat-release ] || [ "$DISTRIBUTION" == "RedHat" ] || [ "$DISTRIBUTION" == "CentOS" ] || [ "$DISTRIBUTION" == "Amazon" ] || [ "$DISTRIBUTION" == "Rocky" ] || [ "$DISTRIBUTION" == "AlmaLinux" ]; then
    OS="RedHat"
    # Some newer distros like Amazon may not have a redhat-release file
  elif [ -f /etc/system-release ] || [ "$DISTRIBUTION" == "Amazon" ]; then
    OS="RedHat"
    # Arista is based off of Fedora14/18 but do not have /etc/redhat-release
  elif [ -f /etc/Eos-release ] || [ "$DISTRIBUTION" == "Arista" ]; then
    OS="RedHat"
    # openSUSE and SUSE use /etc/SuSE-release or /etc/os-release
  elif [ -f /etc/SuSE-release ] || [ "$DISTRIBUTION" == "SUSE" ] || [ "$DISTRIBUTION" == "openSUSE" ]; then
    OS="SUSE"
  elif [ "$DISTRIBUTION" == "Container-Optimized OS" ]; then
    OS="GCOS"
  elif [ "$DISTRIBUTION" == "Flatcar Container Linux" ]; then
    OS="Flatcar"
  elif [ "$DISTRIBUTION" == "Clear Linux OS" ]; then
    OS="ClearLinux"
  elif [ "$DISTRIBUTION" == "Alpine" ]; then
    OS="Alpine"
    SERVICE_MANAGER="openrc"
  elif [ -f /etc/gentoo-release ] || [ "$DISTRIBUTION" == "Gentoo" ]; then
    OS="Gentoo"
    if command -v rc-update &> /dev/null; then
      SERVICE_MANAGER="openrc"
    elif command -v systemctl &> /dev/null; then
      SERVICE_MANAGER="systemd"
    else
      error "No service manager found on Gentoo - must have either openrc or systemd installed"
      exit 1
    fi
    info "Detected service manager is $SERVICE_MANAGER"
  elif [ -f /etc/photon-release ]; then
    OS="Photon"
  else
    error "Unsupported distribution: $DISTRIBUTION"
    exit 1
  fi

  info "Detected OS is $OS"
  DISTRIBUTION="${DISTRIBUTION:-$OS}"
  export WIZ_LINUX_DISTRO="$DISTRIBUTION"
}

check_root() {
  if [ "$UID" != "0" ]; then
    error "Please run this script as root"
    exit 1
  fi
}

check_tmp_dir() {
  if [ ! -w "${TMP_DIR}" ]; then
    error "${TMP_DIR} is not writable. please set TMP_DIR to a writable temp directory and try again."
    exit 1
  fi
}

check_arguments() {
  # Check if WIZ_FIXED_DEFS_VERSION matches major.minor.patch format
  if [ -n "$WIZ_FIXED_DEFS_VERSION" ]; then
    if ! is_semver "$WIZ_FIXED_DEFS_VERSION"; then
      error "WIZ_FIXED_DEFS_VERSION must be in major.minor.patch format (e.g. 1.2.3)"
      exit 1
    fi
  fi

  # Disabling runtime detection requires disk scanner to be enabled
  if [ "$WIZ_DISABLE_RUNTIME_DETECTION" = "1" ] && [ "$WIZ_DISK_SCANNER" != "1" ]; then
    error "WIZ_DISABLE_RUNTIME_DETECTION requires WIZ_DISK_SCANNER to be enabled"
    exit 1
  fi
}

avoid_reinstall() {
  if [ -z "$NO_REINSTALL" ] && ! is_env_enabled "$WIZ_NO_REINSTALL"; then
    return
  fi

  if [ -f "${SENSOR_LEGACY_CONFIG_FILE}" ] || [ -f "${SENSOR_ENV_FILE}" ]; then
    info "Wiz sensor is already installed. To reinstall, please remove the existing installation and try again."
    exit 0
  fi
}

check_update_policy() {
  if [ "$CONTAINER_INSTALL" = "1" ] && [ -z "$WIZ_SENSOR_VERSION" ]; then
    export WIZ_SENSOR_VERSION="v1"
  fi
}

create_legacy_config_file() {
  echo "# Wiz Sensor configuration file" > "$SENSOR_LEGACY_CONFIG_FILE"
  # Add all environment variables starting with WIZ_ to the config file

  # check whether compgen -e is supported
  # (verify that PATH env var exists, as compgen fails silently in case of unknown param)
  if compgen -e | grep PATH &> /dev/null; then
    for key in $(compgen -e); do
      if [[ $key == WIZ_* ]]; then
        echo "${key#WIZ_}: ${!key}" >> "$SENSOR_LEGACY_CONFIG_FILE"
      fi
    done
  else
    WIZ_ENV_VARS=$(env | grep '^WIZ_' | sed -e 's/^WIZ_//' -e 's/^\([^=]*\)=\(.*\)$/\1: \2/')
    echo "${WIZ_ENV_VARS}" > "$SENSOR_LEGACY_CONFIG_FILE"
  fi

  echo "SCRIPT_VERSION: 1.0.13286" >> "$SENSOR_LEGACY_CONFIG_FILE"
  chown "root:root" "$SENSOR_LEGACY_CONFIG_FILE" || {
    error "Failed to set ownership on $SENSOR_LEGACY_CONFIG_FILE"
    exit 1
  }
  chmod 400 "$SENSOR_LEGACY_CONFIG_FILE" || {
    error "Failed to set permissions on $SENSOR_LEGACY_CONFIG_FILE"
    exit 1
  }
}

install_repository_package_redhat() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    # Try to remove any existing wiz-sensor package before installing the new one if install only mode is enabled to avoid running the after_upgrade script
    "$(redhat_package_manager)" -y remove wiz-sensor || true
  fi

  info "Installing YUM sources for Wiz"

  if [ -z "$SKIP_ADD_REPOSITORY" ]; then
    track_added_repo_file /etc/yum.repos.d/wiz.repo
    cat << EOF > /etc/yum.repos.d/wiz.repo
[wiz]
name=Wiz, Inc.
baseurl=${SENSOR_YUM_BASEURL}
enabled=1
gpgcheck=${YUM_GPGCHECK}
repo_gpgcheck=0
priority=1
${YUM_GPGKEY_LINE}
EOF
  fi

  package="wiz-sensor"
  version=$(get_sensor_package_version)
  if [ -n "$version" ]; then
    # rpm: convert '-' to '_'
    package+=-$(echo "$version" | tr '-' '_')
  fi

  pkg_mgr=$(redhat_package_manager)
  install_args=()
  if [ "$pkg_mgr" = "dnf" ]; then
    install_args+=(--best)
  fi
  "$pkg_mgr" -y clean metadata
  "$pkg_mgr" -y --disablerepo='*' --enablerepo='wiz' install "${install_args[@]}" "$package" || "$pkg_mgr" -y install "${install_args[@]}" "$package"
}

install_repository_package_suse() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    # Try to remove any existing wiz-sensor package before installing the new one if install only mode is enabled to avoid running the after_upgrade script
    zypper --non-interactive rm wiz-sensor || true
  fi

  # Install yum repo for Wiz
  if [ -z "$SKIP_ADD_REPOSITORY" ]; then
    track_added_repo_file /etc/zypp/repos.d/wiz.repo
    cat << EOF > /etc/zypp/repos.d/wiz.repo
[wiz]
name=Wiz, Inc.
baseurl=${SENSOR_YUM_BASEURL}
enabled=1
gpgcheck=${YUM_GPGCHECK}
repo_gpgcheck=0
priority=1
${YUM_GPGKEY_LINE}
EOF
    zypper --non-interactive --gpg-auto-import-keys refresh wiz
  fi

  package="wiz-sensor"
  version=$(get_sensor_package_version)
  if [ -n "$version" ]; then
    # rpm: convert '-' to '_'
    package+=-$(echo "$version" | tr '-' '_')
  fi

  zypper --non-interactive --gpg-auto-import-keys install -r wiz "$package" \
    || zypper --non-interactive --gpg-auto-import-keys install "$package"
}

verify_debian_package_signature() {
  pkg_file=$1
  if [ "$OS" = "Debian" ]; then
    if ! curl_proxy --retry 5 "$PACKAGE_PUBLIC_KEY_URL" | gpg --import; then
      error "Failed to import public key"
      exit 1
    fi

    if ! gpg --verify "$pkg_file"; then
      error "Package signature verification failed"
      exit 1
    fi
  fi
}

install_repository_package_debian() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    # Try to remove any existing wiz-sensor package before installing the new one if install only mode is enabled to avoid running the after_upgrade script
    apt-get remove -y --purge wiz-sensor || true
  fi

  apt_trusted_d_keyring="/etc/apt/trusted.gpg.d/wiz-archive-keyring.gpg"
  apt_usr_share_keyring="/usr/share/keyrings/wiz-archive-keyring.gpg"

  info "Installing apt-transport-https and gnupg"
  apt-get update || warn "'apt-get update' failed, the script will not install the latest version of apt-transport-https\n"
  apt-get install -y apt-transport-https gnupg

  if [ -z "$SKIP_ADD_REPOSITORY" ]; then
    info "Installing APT sources for Wiz"
    track_added_repo_file /etc/apt/sources.list.d/wiz.list
    if [ "$APT_REPO_UNSIGNED" = "1" ]; then
      # unsigned mirror: trust the repo and skip key import entirely
      sh -c "echo 'deb [trusted=yes] ${SENSOR_APT_REPO_SPEC}' > /etc/apt/sources.list.d/wiz.list"
    else
      sh -c "echo 'deb [signed-by=${apt_usr_share_keyring}] ${SENSOR_APT_REPO_SPEC}' > /etc/apt/sources.list.d/wiz.list"

      if [ ! -f $apt_usr_share_keyring ]; then
        touch $apt_usr_share_keyring
      fi
      # ensure that the _apt user used on Ubuntu/Debian systems to read GPG keyrings
      # can read our keyring
      chmod a+r $apt_usr_share_keyring || {
        error "Failed to set permissions on $apt_usr_share_keyring"
        exit 1
      }

      curl_proxy --retry 5 -o "${TMP_DIR}/wiz_repo_public_key.gpg" "${SENSOR_APT_KEY_URL}"
      gpg --import --batch --no-default-keyring --keyring "$apt_usr_share_keyring" < "${TMP_DIR}/wiz_repo_public_key.gpg"

      release_version="$(grep VERSION_ID /etc/os-release | cut -d = -f 2 | xargs echo | cut -d "." -f 1)"
      if { [ "$DISTRIBUTION" == "Debian" ] && [ "$release_version" -lt 9 ]; } \
        || { [ "$DISTRIBUTION" == "Ubuntu" ] && [ "$release_version" -lt 16 ]; }; then
        # copy with -a to preserve file permissions
        cp -a $apt_usr_share_keyring $apt_trusted_d_keyring
      fi
    fi

    apt-get update -o Dir::Etc::sourcelist="sources.list.d/wiz.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0"
  fi

  package="wiz-sensor"
  version=$(get_sensor_package_version)
  if [ -n "$version" ]; then
    # deb: convert '_' to '-'
    package+=$(echo "=$version" | tr '_' '-')
  fi

  if [ "$APT_GPGCHECK" -eq 1 ]; then
    pushd /tmp
    apt-get download "$package"
    # need ls -t to pick newest .deb; find has no sort-by-mtime
    # shellcheck disable=SC2012
    pkg_file=$(ls -t ./*.deb | head -n 1)
    verify_debian_package_signature "$pkg_file"
    dpkg -i "$pkg_file"
    popd
  else
    apt-get install -y --force-yes "$package"
  fi
}

install_package() {
  if [ "$OS" = "RedHat" ]; then
    install_repository_package_redhat
  elif [ "$OS" = "SUSE" ]; then
    install_repository_package_suse
  elif [ "$OS" = "Debian" ]; then
    install_repository_package_debian
  elif [[ "$DOCKER_ONLY_OS_LIST" =~ $OS ]]; then
    error "$OS only supports Docker installation. Please set DOCKER_INSTALL=1 and try again."
    exit 1
  fi

  # The package is installed; the repository stays even if a later step fails.
  ADDED_REPO_FILE=""
}

install_local_package() {
  if [ "$OS" = "RedHat" ]; then
    "$(redhat_package_manager)" install -y "$LOCAL_PACKAGE"
  elif [ "$OS" = "SUSE" ]; then
    zypper install -y "$LOCAL_PACKAGE"
  elif [ "$OS" = "Debian" ]; then
    dpkg -i "$LOCAL_PACKAGE"
  else
    error "Unsupported OS for local package installation"
    exit 1
  fi
}

create_sensor_env_file() {
  if [ "$OS" = "GCOS" ]; then
    sensor_type="gcos"
  elif [ "$CONTAINERD_INSTALL" = "1" ]; then
    sensor_type="container"
    container_runtime="CONTAINER_RUNTIME=containerd"
  elif [ "$DOCKER_INSTALL" = "1" ]; then
    sensor_type="container"
    container_runtime="CONTAINER_RUNTIME=docker"
  elif [ "$PODMAN_INSTALL" = "1" ]; then
    sensor_type="container"
    container_runtime="CONTAINER_RUNTIME=podman"
  else
    sensor_type="vm"
  fi

  # Workstation sensors install like VM sensors (natively or as a container).
  if [ "$WIZ_SENSOR_TYPE" = "workstation" ]; then
    sensor_type="workstation"
  fi

  if [ -n "$HTTP_PROXY_CERT_PATH" ]; then
    mkdir -p "${SENSOR_HOST_STORE}/proxy-files" || {
      error "Failed to create directory ${SENSOR_HOST_STORE}/proxy-files"
      exit 1
    }
    cp "$HTTP_PROXY_CERT_PATH" "${SENSOR_HOST_STORE}/proxy-files/proxy.pem" || {
      error "Failed to copy proxy certificate to ${SENSOR_HOST_STORE}/proxy-files/proxy.pem"
      exit 1
    }
    export WIZ_HTTP_PROXY_CERT_PATH="/wiz-host-cache/proxy-files/proxy.pem"
  fi

  additional_env=""
  if [ "${WIZ_DISK_SCANNER}" = "1" ]; then
    additional_env="${additional_env}"$'\n'"WIZ_DISK_SCAN_SHARED_VOL=/wiz-sensor-share"
  fi

  cat << EOF > "$SENSOR_ENV_FILE"
WIZ_HOST_STORE=/wiz-host-cache/
WIZ_TMP_STORE=/wiz-host-cache/tmp_store/
WIZ_RAMFS_STORE=/tmp/ramfs/
SENSOR_TYPE=${sensor_type}
LOG_FILE=/wiz-host-cache/sensor_logs/sensor.log
SCRIPT_VERSION=1.0.13286
${additional_env}
${container_runtime}
EOF

  # Add all environment variables starting with WIZ_ to the config file
  # (use null byte as delimiter to handle values with newlines)
  env -0 | while IFS='' read -r -d '' line; do
    if [[ "$line" == WIZ_* ]]; then
      key="${line%%=*}"
      key_no_prefix="${key#WIZ_}"

      # Sensor should listen on default address in container mode
      # The METRICS_LISTEN_ADDR will be used to expose the port on the host network
      if [ "$CONTAINER_INSTALL" = "1" ] && [ "$key_no_prefix" = "METRICS_LISTEN_ADDR" ]; then
        continue
      fi

      # Check if this env is in the BASE64_ENVS list
      if echo "${BASE64_ENCODED_ENVS[@]}" | grep -q "$key_no_prefix"; then
        encoded_value=$(printf '%s' "${!key}" | base64 -w0)
        echo "${key_no_prefix}=base64:${encoded_value}" >> "$SENSOR_ENV_FILE"
      else
        echo "${key_no_prefix}=${!key}" >> "$SENSOR_ENV_FILE"
      fi
    fi
  done

  chown "root:root" "${SENSOR_ENV_FILE}" || {
    error "Failed to set ownership on ${SENSOR_ENV_FILE}"
    exit 1
  }
  chmod 400 "${SENSOR_ENV_FILE}" || {
    error "Failed to set permissions on ${SENSOR_ENV_FILE}"
    exit 1
  }
}

create_sensor_service_file() {
  local image_ref=$1
  sensor_additional_opts=""
  if [ "$DOCKER_INSTALL" = "1" ] || [ "$PODMAN_INSTALL" = "1" ]; then
    sensor_additional_opts="${sensor_additional_opts} --security-opt label=disable"
  fi
  if [ "$DOCKER_INSTALL" = "1" ]; then
    sensor_additional_opts="${sensor_additional_opts} --security-opt no-new-privileges=false"
  fi
  if [ "$CONTAINER_INSTALL" = "1" ] && [ -n "$WIZ_METRICS_PORT" ]; then
    metrics_addr="${WIZ_METRICS_PORT}"
    if [ -n "$WIZ_METRICS_LISTEN_ADDR" ]; then
      metrics_addr="${WIZ_METRICS_LISTEN_ADDR}:${WIZ_METRICS_PORT}"
    fi
    sensor_additional_opts="${sensor_additional_opts} -p ${metrics_addr}:${WIZ_METRICS_PORT}"
    info "Container will expose metrics on ${metrics_addr}"
  fi

  if [ "$OS" = "Flatcar" ]; then
    sensor_additional_opts="${sensor_additional_opts} --security-opt label=type:unconfined_t"
  fi

  if [ "${WIZ_HOST_NETWORK,,}" == "true" ]; then
    sensor_additional_opts="${sensor_additional_opts} --network host"
  fi

  if [ "${WIZ_DISK_SCANNER}" = "1" ]; then
    sensor_additional_opts="${sensor_additional_opts} -v ${SENSOR_HOST_STORE}/wiz-sensor-share:/wiz-sensor-share"
  fi

  if [ "${WIZ_PRIVILEGED_INSTALL,,}" == "true" ] && [ "${WIZ_DISALLOW_RUNTIME_RESPONSE,,}" == "true" ]; then
    error "WIZ_PRIVILEGED_INSTALL and WIZ_DISALLOW_RUNTIME_RESPONSE are incompatible. In privileged mode, the container has all capabilities including KILL."
    exit 1
  fi

  if [ "${WIZ_PRIVILEGED_INSTALL,,}" == "true" ]; then
    sensor_user_opts="-u 0:0"
    sensor_security_opts="--privileged"
  else
    sensor_runtime_response=$([ "${WIZ_DISALLOW_RUNTIME_RESPONSE,,}" == "true" ] && echo "--cap-drop=KILL" || echo "--cap-add=KILL")
    sensor_sys_rawio=$([ "${WIZ_DROP_SYS_RAWIO,,}" == "true" ] && echo "" || echo "--cap-add=SYS_RAWIO")
    sensor_user_opts="-u 2202:2202"
    sensor_security_opts="--security-opt apparmor=unconfined \\
    --security-opt seccomp=unconfined \\
    --cap-add=SYS_ADMIN \\
    --cap-add=SYS_CHROOT \\
    --cap-add=SYS_RESOURCE \\
    ${sensor_sys_rawio} \\
    --cap-add=DAC_OVERRIDE \\
    --cap-add=DAC_READ_SEARCH \\
    --cap-add=NET_ADMIN \\
    --cap-add=NET_RAW \\
    --cap-add=IPC_LOCK \\
    --cap-add=FOWNER \\
    --cap-add=SYS_PTRACE \\
    --cap-add=SYSLOG \\
    --cap-add=LEASE \\
    ${sensor_runtime_response}"
  fi

  service_name="wiz-sensor"
  service_description="Wiz Sensor"
  service_pre_commands=(
    "${cli_tool_full_path} pull ${image_ref}"
    "${cli_tool_full_path} stop wiz-sensor"
    "${cli_tool_full_path} rm wiz-sensor"
  )
  service_command="${cli_tool_full_path}"
  service_command_args="run --name wiz-sensor \\
    --mount type=bind,source=/sys/kernel/debug,target=/sys/kernel/debug,readonly \\
    --mount type=tmpfs,destination=/tmp,tmpfs-size=100m \\
    --env-file ${SENSOR_ENV_FILE} \\
    -v ${SENSOR_HOST_STORE}:/wiz-host-cache \\
    ${sensor_user_opts} \\
    --pid host \\
    --ipc host \\
    --read-only \\
    ${sensor_security_opts} \\
    ${sensor_additional_opts} \\
    ${image_ref}"
  service_stop_command="${cli_tool_full_path} stop wiz-sensor"

  if [ "$cli_tool" = "ctr" ]; then
    # ctr applies no AppArmor or seccomp profile, and its capability names start with CAP_.
    sensor_security_opts=$(printf '%s\n' "$sensor_security_opts" | sed -E -e '/--security-opt/d' -e 's/--cap-(add|drop)=/&CAP_/' | sed '1s/^ *//')
    # ctr has no login command, and a pull needs the registry password in its command
    # line. As a result, the service does not pull the image.
    service_pre_commands=(
      "${cli_tool_full_path} task kill --signal SIGKILL wiz-sensor"
      "${cli_tool_full_path} task delete --force wiz-sensor"
      "${cli_tool_full_path} container rm wiz-sensor"
    )
    # ctr has no container network, so the sensor always uses the host network.
    service_command_args="run --rm \\
    --mount type=bind,src=/sys/kernel/debug,dst=/sys/kernel/debug,options=rbind:ro \\
    --mount type=tmpfs,src=tmpfs,dst=/tmp,options=size=100m \\
    --env-file ${SENSOR_ENV_FILE} \\
    --mount type=bind,src=${SENSOR_HOST_STORE},dst=/wiz-host-cache,options=rbind:rw \\
    --user ${sensor_user_opts#-u } \\
    --with-ns pid:/proc/1/ns/pid \\
    --with-ns ipc:/proc/1/ns/ipc \\
    --net-host \\
    --read-only \\
    --allow-new-privs \\
    ${sensor_security_opts} \\
    ${image_ref} wiz-sensor"
    service_stop_command="${cli_tool_full_path} task kill wiz-sensor"
  fi

  if [ "$SERVICE_MANAGER" = "systemd" ]; then
    create_systemd_file
  elif [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    create_sysvinit_file
  else
    create_openrc_file
  fi
}

prepare_proxy_cert_file() {
  if [ -n "$WIZ_HTTP_PROXY_CERT" ]; then
    mkdir -p "$TMP_DIR/proxy-files" || {
      error "Failed to create directory $TMP_DIR/proxy-files"
      exit 1
    }
    echo "$WIZ_HTTP_PROXY_CERT" | base64 -d > "$TMP_DIR/proxy-files/proxy.pem"
    export HTTP_PROXY_CERT_PATH="$TMP_DIR/proxy-files/proxy.pem"
  elif [ -n "$WIZ_HTTP_PROXY_CERT_PATH" ]; then
    export HTTP_PROXY_CERT_PATH="$WIZ_HTTP_PROXY_CERT_PATH"
  fi
  unset WIZ_HTTP_PROXY_CERT_PATH
}

create_disk_scanner_env_file() {
  DISK_SCANNER_ENV_FILE=${DISK_SCANNER_HOST_STORE}/disk-scanner.env
  if [ -n "$HTTP_PROXY_CERT_PATH" ]; then
    mkdir -p "${DISK_SCANNER_HOST_STORE}/proxy-files" || {
      error "Failed to create directory ${DISK_SCANNER_HOST_STORE}/proxy-files"
      exit 1
    }
    cp "$HTTP_PROXY_CERT_PATH" "${DISK_SCANNER_HOST_STORE}/proxy-files/proxy.pem" || {
      error "Failed to copy proxy certificate to ${DISK_SCANNER_HOST_STORE}/proxy-files/proxy.pem"
      exit 1
    }
    if [ "$CONTAINER_INSTALL" = "1" ]; then
      chown -R 2202:2202 "${DISK_SCANNER_HOST_STORE}/proxy-files" || {
        error "Failed to set ownership on ${DISK_SCANNER_HOST_STORE}/proxy-files"
        exit 1
      }
    fi
    container_cert_path="SSL_CERT_FILE=/wiz-host-cache/proxy-files/proxy.pem"
  fi

  writeable_folder="${TMP_DIR}"
  if [ "$CONTAINERD_INSTALL" = "1" ]; then
    container_runtime="CONTAINER_RUNTIME=containerd"
  elif [ "$DOCKER_INSTALL" = "1" ]; then
    container_runtime="CONTAINER_RUNTIME=docker"
  elif [ "$PODMAN_INSTALL" = "1" ]; then
    container_runtime="CONTAINER_RUNTIME=podman"
  else
    writeable_folder="/wiz-host-cache"
  fi

  cat << EOF > "$DISK_SCANNER_ENV_FILE"
SCRIPT_VERSION=1.0.13286
https_proxy=${WIZ_HTTP_PROXY_URL}
WIZ_ONPREM_ORCHESTRATOR_WRITEABLE_FOLDER=${writeable_folder}
${container_cert_path}
${container_runtime}
EOF

  # Add all environment variables starting with WIZ_ to the config file
  # (use null byte as delimiter to handle values with newlines)
  env -0 | while IFS='' read -r -d '' line; do
    if [[ "$line" == WIZ_* ]]; then
      echo "${line}" >> "$DISK_SCANNER_ENV_FILE"
    fi
  done

  chown "root:root" "${DISK_SCANNER_ENV_FILE}" || {
    error "Failed to set ownership on ${DISK_SCANNER_ENV_FILE}"
    exit 1
  }
  chmod 400 "${DISK_SCANNER_ENV_FILE}" || {
    error "Failed to set permissions on ${DISK_SCANNER_ENV_FILE}"
    exit 1
  }
}

create_openrc_file() {
  local service_file="/etc/init.d/${service_name}"

  pre_commands=""
  for pre_command in "${service_pre_commands[@]}"; do
    pre_commands+="${pre_command}; "
  done

  service_dependencies=""
  if [ "${service_dependency}" != "" ]; then
    service_dependencies="\
depend() {
  need ${service_dependency}
  after ${service_dependency}
}"
  fi

  cat << EOF > ${service_file}
#!/sbin/openrc-run

description="${service_description}"
supervisor="supervise-daemon"
command="/bin/bash"
command_args="-c \"export DOCKER_CONFIG=${DOCKER_CONFIG}; ${pre_commands} ${service_command} ${service_command_args}\""
respawn_delay=15
respawn_max=0

${service_dependencies}
EOF

  chmod +x ${service_file} || {
    error "Failed to set permissions on ${service_file}"
    exit 1
  }
}

create_sysvinit_file() {
  local service_file="/etc/init.d/${service_name}"

  pre_commands=""
  for pre_command in "${service_pre_commands[@]}"; do
    pre_commands+="  ${pre_command} || true"$'\n'
  done

  service_dependencies_lsb="\$network \$remote_fs"
  if [ "${service_dependency}" != "" ]; then
    service_dependencies_lsb="${service_dependencies_lsb} ${service_dependency}"
  fi

  # `unless-stopped` (not `always`) so that `service wiz-sensor stop` is
  # honored across docker daemon restarts — otherwise an uninstalled sensor
  # would resurrect after `dockerd` bounces.
  local sysvinit_command_args="${service_command_args/run /run -d --restart=unless-stopped }"

  cat << EOF > ${service_file}
#!/bin/sh
### BEGIN INIT INFO
# Provides:          ${service_name}
# Required-Start:    ${service_dependencies_lsb}
# Required-Stop:     ${service_dependencies_lsb}
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: ${service_description}
### END INIT INFO

export DOCKER_CONFIG=${DOCKER_CONFIG}

case "\$1" in
  start)
${pre_commands}
    ${service_command} ${sysvinit_command_args}
    ;;
  stop)
    ${service_stop_command}
    ;;
  restart|force-reload)
    "\$0" stop
    "\$0" start
    ;;
  status)
    if ${service_command} inspect -f '{{.State.Running}}' ${service_name} 2>/dev/null | grep -q true; then
      echo "${service_name} is running"
      exit 0
    else
      echo "${service_name} is not running"
      exit 3
    fi
    ;;
  *)
    echo "Usage: \$0 {start|stop|restart|force-reload|status}"
    exit 1
    ;;
esac
EOF

  chmod +x ${service_file} || {
    error "Failed to set permissions on ${service_file}"
    exit 1
  }
}

create_systemd_file() {
  local service_file="${systemd_dir}/${service_name}.service"
  ExecStartPre=""
  for pre_command in "${service_pre_commands[@]}"; do
    ExecStartPre+="ExecStartPre=-${pre_command}"$'\n'
  done

  service_dependencies=""
  if [ "${service_dependency}" != "" ]; then
    service_dependencies="\
After=${service_dependency}.service
Requires=${service_dependency}.service"
  fi

  cat << EOF > ${service_file}
[Unit]
Description=${service_description}
${service_dependencies}

[Service]
Restart=always
RestartSec=15
TimeoutStartSec=0
Delegate=yes

Environment=DOCKER_CONFIG=${DOCKER_CONFIG}
${ExecStartPre}
ExecStart=${service_command} ${service_command_args}
ExecStop=${service_stop_command}

[Install]
WantedBy=multi-user.target
EOF
}

root_mount_supports_slave_propagation() {
  local mount_point mount_metadata

  [ -r /proc/self/mountinfo ] || return 1

  while IFS=" " read -r _ _ _ _ mount_point _ mount_metadata; do
    [ "$mount_point" = "/" ] || continue

    mount_metadata=${mount_metadata%%" - "*}
    case " $mount_metadata " in
      *" shared:"* | *" master:"*) return 0 ;;
    esac
    return 1
  done < /proc/self/mountinfo

  return 1
}

get_disk_scanner_mount_propagation() {
  local mount_propagation=${WIZ_DISK_SCANNER_MOUNT_PROPAGATION:-slave}

  case "$mount_propagation" in
    private) ;;
    slave)
      if ! root_mount_supports_slave_propagation; then
        error "This host's root mount doesn't support shared or slave mount propagation, which is required for the workload scanner to scan new mounts. You can suppress this error by running the installer with WIZ_DISK_SCANNER_MOUNT_PROPAGATION=private."
        exit 1
      fi
      ;;
    *)
      error "WIZ_DISK_SCANNER_MOUNT_PROPAGATION must be one of: private, slave."
      return 1
      ;;
  esac

  echo "$mount_propagation"
}

create_disk_scanner_service_file() {
  local image_ref=$1
  disk_scanner_additional_opts=""

  if [ "$DOCKER_INSTALL" = "1" ] || [ "$PODMAN_INSTALL" = "1" ]; then
    disk_scanner_additional_opts="${disk_scanner_additional_opts} --security-opt label=disable"
  fi
  if [ "$DOCKER_INSTALL" = "1" ]; then
    disk_scanner_additional_opts="${disk_scanner_additional_opts} --security-opt no-new-privileges=false"
  fi

  if [ "$OS" = "Flatcar" ]; then
    disk_scanner_additional_opts="${disk_scanner_additional_opts} --security-opt label=type:unconfined_t"
  fi

  if [ "${WIZ_HOST_NETWORK,,}" == "true" ]; then
    disk_scanner_additional_opts="${disk_scanner_additional_opts} --network host"
  fi

  if [ -z "${DISK_SCANNER_MOUNTING_OPTS+x}" ]; then
    DISK_SCANNER_MOUNTING_OPTS="readonly"
    local mount_propagation
    mount_propagation=$(get_disk_scanner_mount_propagation)
    if [ "$mount_propagation" = "slave" ]; then
      DISK_SCANNER_MOUNTING_OPTS+=",bind-propagation=rslave"
    fi
  fi

  if [ "${WIZ_PRIVILEGED_INSTALL,,}" == "true" ]; then
    ds_user_opts="-u 0:0"
    ds_security_opts="--privileged"
  else
    ds_user_opts="-u 2202:2202"
    ds_security_opts="--cap-add=SYS_ADMIN \
    --cap-add=DAC_OVERRIDE \
    --cap-add=DAC_READ_SEARCH \
    --cap-add=FOWNER \
    --cap-add=CHOWN \
    --cap-add=SETPCAP \
    --cap-add=SYS_PTRACE \
    --cap-add=IPC_LOCK \
    --security-opt apparmor=unconfined \
    --security-opt seccomp=unconfined"
  fi

  service_name="wiz-disk-scanner"
  service_description="Wiz Disk Scanner"
  service_pre_commands=(
    "${cli_tool_full_path} pull ${image_ref}"
    "${cli_tool_full_path} stop wiz-disk-scanner"
    "${cli_tool_full_path} rm -v wiz-disk-scanner"
  )
  service_command="${cli_tool_full_path}"
  service_command_args="run --name wiz-disk-scanner --rm \
    --cpus=${WIZ_DISK_SCANNER_CPU_LIMIT} --memory=${WIZ_DISK_SCANNER_MEMORY_LIMIT} \
    --mount type=volume,dst=/tmp \
    --mount type=bind,src=/,dst=/host${DISK_SCANNER_MOUNTING_OPTS:+,$DISK_SCANNER_MOUNTING_OPTS} \
    --pid host \
    -v ${SENSOR_HOST_STORE}/wiz-sensor-share:/wiz-sensor-share \
    -v ${DISK_SCANNER_HOST_STORE}:/wiz-host-cache \
    ${ds_user_opts} \
    ${ds_security_opts} \
    ${disk_scanner_additional_opts} \
    --env-file ${DISK_SCANNER_ENV_FILE} \
    ${image_ref}"
  service_stop_command="${cli_tool_full_path} stop wiz-disk-scanner"

  if [ "$SERVICE_MANAGER" = "systemd" ]; then
    create_systemd_file
  elif [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    create_sysvinit_file
  else
    create_openrc_file
  fi
}

install_container() {
  component=$1

  if [ "$CONTAINERD_INSTALL" = "1" ]; then
    cli_tool="nerdctl"
    # Some hosts have containerd but not nerdctl, for example Container-Optimized OS.
    # These hosts use ctr, which is a part of containerd.
    if ! command -v nerdctl &> /dev/null && command -v ctr &> /dev/null; then
      cli_tool="ctr"
    fi
  elif [ "$DOCKER_INSTALL" = "1" ]; then
    cli_tool="docker"
  elif [ "$PODMAN_INSTALL" = "1" ]; then
    cli_tool="podman"
  fi

  if ! command -v "$cli_tool" &> /dev/null; then
    error "$cli_tool is not installed. Please install $cli_tool and try again."
    exit 1
  fi

  if [ "$cli_tool" = "docker" ] && ! docker info &> /dev/null; then
    error "Docker is not running. Please start Docker and try again."
    exit 1
  elif [ "$cli_tool" = "nerdctl" ] && ! nerdctl info &> /dev/null; then
    error "Containerd is not running. Please start Containerd and try again."
    exit 1
  elif [ "$cli_tool" = "ctr" ] && ! ctr version &> /dev/null; then
    error "Containerd is not running. Please start Containerd and try again."
    exit 1
  fi

  if [ "$cli_tool" = "ctr" ]; then
    # The ctr service is available for systemd only. ctr cannot publish ports, and there is
    # no ctr command for the disk scanner container.
    if [ "${SERVICE_MANAGER}" != "systemd" ]; then
      error "A Containerd installation with ctr requires systemd. Please install nerdctl and try again."
      exit 1
    fi
    if [ -n "$WIZ_METRICS_PORT" ] || [ "$WIZ_DISK_SCANNER" = "1" ]; then
      error "WIZ_METRICS_PORT and WIZ_DISK_SCANNER are not supported in a Containerd installation with ctr. Please install nerdctl and try again."
      exit 1
    fi
  fi

  if [ "${SERVICE_MANAGER}" = "systemd" ] && ! has_systemd; then
    error "Systemd is not installed. Please install systemd and try again."
    exit 1
  elif [ "${SERVICE_MANAGER}" = "openrc" ] && ! has_openrc; then
    error "OpenRC is not installed. Please install OpenRC and try again."
    exit 1
  elif [ "${SERVICE_MANAGER}" = "sysvinit" ] && ! has_sysvinit; then
    error "sysvinit tools (update-rc.d, service) are not installed. Please install sysv-rc and try again."
    exit 1
  fi

  export DOCKER_CONFIG=${WIZ_DIR}/sensor/docker-config

  local pull_command=("$cli_tool" pull)
  if [ "$cli_tool" = "ctr" ]; then
    pull_command=(ctr images pull)
  fi

  if [ "$CONTAINER_REGISTRY_LOGIN" -eq 1 ]; then
    if [[ -z "$PULL_USERNAME" || -z "$PULL_PASSWORD" ]]; then
      error "Missing PULL_USERNAME or PULL_PASSWORD environment variables."
      exit 1
    fi

    if [ "$cli_tool" = "ctr" ]; then
      # ctr has no login command. It gets the registry credentials for each pull.
      pull_command+=(--user "${PULL_USERNAME}:${PULL_PASSWORD}")
    else
      login_successful=$(timeout 5 "$cli_tool" login "$CONTAINER_REGISTRY" -u "$PULL_USERNAME" -p "$PULL_PASSWORD" > /dev/null 2>&1 && echo 1 || echo 0)
      if [ "$login_successful" -eq 0 ]; then
        error "Failed to login to Wiz container registry."
        exit 1
      fi
    fi
  fi

  local image_ref
  if [ "$component" = "sensor" ]; then
    image_ref="${CONTAINER_REGISTRY}/${SENSOR_REPOSITORY}:${WIZ_SENSOR_VERSION}"
  elif [ "$component" = "disk-scanner" ]; then
    image_ref="${CONTAINER_REGISTRY}/${WIZ_DISK_SCANNER_REPOSITORY}:${WIZ_DISK_SCANNER_VERSION}"
  fi

  info "Pulling container image: ${image_ref}"
  if ! "${pull_command[@]}" "${image_ref}"; then
    error "Failed to pull image '${image_ref}'."
    exit 1
  fi

  cli_tool_full_path=$(command -v "$cli_tool" 2> /dev/null)
  if [ -z "$cli_tool_full_path" ]; then
    case "$cli_tool" in
      "nerdctl")
        cli_tool_full_path="/usr/local/bin/nerdctl"
        ;;
      "podman")
        cli_tool_full_path="/usr/bin/podman"
        ;;
      "docker")
        cli_tool_full_path="/usr/bin/docker"
        ;;
      *)
        error "Unknown CLI tool: $cli_tool"
        exit 1
        ;;
    esac
  fi

  if [ "$DOCKER_INSTALL" = "1" ]; then
    service_dependency='docker'
  elif [ "$CONTAINERD_INSTALL" = "1" ]; then
    service_dependency='containerd'
  fi

  if [ "$OS" = "ClearLinux" ]; then
    systemd_dir="/usr/lib/systemd/system"
  else
    systemd_dir="/etc/systemd/system"
  fi

  if [ "$component" = "sensor" ]; then
    create_sensor_service_file "${image_ref}"
  elif [ "$component" = "disk-scanner" ]; then
    create_disk_scanner_service_file "${image_ref}"
  fi
}

silent() {
  "$@" > /dev/null 2>&1
}

has_systemd() {
  { [ -d "/lib/systemd/system/" ] || [ -d "/usr/lib/systemd/system" ]; } && silent command -v systemctl
}

has_openrc() {
  silent command -v openrc
}

has_sysvinit() {
  silent command -v update-rc.d && silent command -v service
}

enable_systemd_services() {
  systemctl enable wiz-sensor.service
  # disk scanner systemctl service is only supported in container installation
  if [ "$CONTAINER_INSTALL" = "1" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    systemctl enable wiz-disk-scanner.service
  fi
}

enable_openrc_services() {
  rc-update add wiz-sensor default
  # disk scanner systemctl service is only supported in container installation
  if [ "$CONTAINER_INSTALL" = "1" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    rc-update add wiz-disk-scanner default
  fi
}

enable_sysvinit_services() {
  update-rc.d wiz-sensor defaults
  # disk scanner service is only supported in container installation
  if [ "$CONTAINER_INSTALL" = "1" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    update-rc.d wiz-disk-scanner defaults
  fi
  # pleaserun's sysv init script writes stdout/stderr to /var/log/wiz-sensor-*.log
  # with no rotation. Container installs use our own init script and don't
  # produce these files.
  if [ "$CONTAINER_INSTALL" != "1" ]; then
    if [ -d /etc/logrotate.d ]; then
      cat > /etc/logrotate.d/wiz-sensor << 'EOF'
/var/log/wiz-sensor-stdout.log
/var/log/wiz-sensor-stderr.log
{
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}
EOF
    else
      warn "logrotate is not installed; the sensor's stdout/stderr logs at /var/log/wiz-sensor-stdout.log and /var/log/wiz-sensor-stderr.log will not be rotated. Install logrotate to enable rotation."
    fi
  fi
}

enable_services() {
  if [ "$SERVICE_MANAGER" = "openrc" ]; then
    enable_openrc_services
  elif [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    enable_sysvinit_services
  elif [ "$SERVICE_MANAGER" = "systemd" ]; then
    enable_systemd_services
  fi
}

is_wiz_sensor_running() {
  if [ "$SERVICE_MANAGER" = "systemd" ]; then
    systemctl is-active --quiet wiz-sensor
  elif [ "$SERVICE_MANAGER" = "openrc" ]; then
    rc-service wiz-sensor status > /dev/null 2>&1
  elif [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    service wiz-sensor status > /dev/null 2>&1
  else
    # Fallback to ps check for unknown service managers
    if ps -eo comm > /dev/null 2>&1; then
      # pgrep may not be available on minimal systems
      # shellcheck disable=SC2009
      ps -eo comm 2> /dev/null | grep -x "wiz-sensor" > /dev/null 2>&1
    else
      # pgrep may not be available on minimal systems
      # shellcheck disable=SC2009
      ps ax 2> /dev/null | grep -E "\\bwiz-sensor\\b" > /dev/null 2>&1
    fi
  fi
}

wait_for_sensor_to_start() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    return 0
  fi

  local wait_seconds=60
  local i=0

  info "Waiting for wiz-sensor to start..."
  while ! is_wiz_sensor_running; do
    if [ $i -ge $wait_seconds ]; then
      warn "wiz-sensor did not start within ${wait_seconds}s. This may indicate a problem - please check sensor logs or contact Wiz support."
      return 1
    fi
    sleep 1
    i=$((i + 1))
  done
  info "wiz-sensor is running"
  return 0
}

stop_component_and_wait() {
  local component_name="${1:-wiz-sensor}"
  local wait_seconds=60

  # Unify stop-and-wait logic for different service managers
  local status_check=""
  local stop_cmd=""
  local warn_label=""

  if [ "$SERVICE_MANAGER" = "systemd" ]; then
    if systemctl is-active --quiet "${component_name}.service"; then
      info "Stopping ${component_name}.service and waiting for it to stop"
      stop_cmd="systemctl stop ${component_name}.service || true"
      status_check="systemctl is-active --quiet ${component_name}.service"
      warn_label="${component_name}.service"
    fi
  elif [ "$SERVICE_MANAGER" = "openrc" ]; then
    if rc-service "$component_name" status | grep -q running; then
      info "Stopping $component_name (openrc) and waiting for it to stop"
      stop_cmd="rc-service $component_name stop || true"
      status_check="rc-service $component_name status | grep -q running"
      warn_label="$component_name"
    fi
  elif [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    if [ -x "/etc/init.d/$component_name" ] && service "$component_name" status > /dev/null 2>&1; then
      info "Stopping $component_name (sysvinit) and waiting for it to stop"
      stop_cmd="service $component_name stop || true"
      status_check="service $component_name status > /dev/null 2>&1"
      warn_label="$component_name"
    fi
  fi

  if [ -n "$status_check" ]; then
    eval "$stop_cmd"
    local i=0
    while eval "$status_check"; do
      if [ $i -ge $wait_seconds ]; then
        warn "$warn_label did not stop within ${wait_seconds}s; proceeding"
        break
      fi
      sleep 1
      i=$((i + 1))
    done
  fi

  if [ "$CONTAINER_INSTALL" = "1" ]; then
    local cli_tool=""
    if [ "$CONTAINERD_INSTALL" = "1" ]; then
      cli_tool="nerdctl"
    elif [ "$DOCKER_INSTALL" = "1" ]; then
      cli_tool="docker"
    elif [ "$PODMAN_INSTALL" = "1" ]; then
      cli_tool="podman"
    fi

    if [ -n "$cli_tool" ] && command -v "$cli_tool" > /dev/null 2>&1; then
      $cli_tool stop "$component_name" > /dev/null 2>&1 || true
      # Guard against old CLI versions without --format; build a single status check command
      local status_check_cmd=""
      if $cli_tool ps -a --format '{{.Names}} {{.Status}}' > /dev/null 2>&1; then
        status_check_cmd="$cli_tool ps -a --format '{{.Names}} {{.Status}}' 2>/dev/null | grep -E '^${component_name}\\b' | grep -qi 'up\|running'"
      else
        status_check_cmd="$cli_tool ps -a 2>/dev/null | grep -E '^${component_name}\\b|\\b${component_name}\\b' | grep -qi 'up\|running\|Up\|UP'"
      fi
      local i=0
      while eval "$status_check_cmd"; do
        if [ $i -ge $wait_seconds ]; then
          warn "$component_name container still running after ${wait_seconds}s; proceeding"
          break
        fi
        sleep 1
        i=$((i + 1))
      done
      $cli_tool rm -v "$component_name" > /dev/null 2>&1 || true
    fi
  fi
}

stop_old_components_and_wait() {
  stop_component_and_wait wiz-sensor
  stop_component_and_wait wiz-disk-scanner

  local i=0
  local wait_seconds=60
  while is_wiz_sensor_running; do
    if [ $i -ge $wait_seconds ]; then
      warn "wiz-sensor process still present after ${wait_seconds}s; proceeding"
      break
    fi
    sleep 1
    i=$((i + 1))
  done
}

start_systemd_services() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    return
  fi

  # wiz-sensor
  if systemctl is-active --quiet wiz-sensor.service; then
    info "wiz-sensor.service is running, restarting (systemd)"
    systemctl daemon-reload
    systemctl restart wiz-sensor.service
  else
    systemctl start wiz-sensor.service
  fi

  # wiz-disk-scanner (only if container install and enabled)
  if [ "$CONTAINER_INSTALL" = "1" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    if systemctl is-active --quiet wiz-disk-scanner.service; then
      info "wiz-disk-scanner.service is running, restarting (systemd)"
      systemctl daemon-reload
      systemctl restart wiz-disk-scanner.service
    else
      systemctl start wiz-disk-scanner.service
    fi
  fi
}

start_openrc_services() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    return
  fi

  # wiz-sensor
  if rc-service wiz-sensor status | grep -q running; then
    info "wiz-sensor is running, restarting (openrc)"
    rc-service wiz-sensor restart
  else
    rc-service wiz-sensor start
  fi

  # wiz-disk-scanner (only if container install and enabled)
  if [ "$CONTAINER_INSTALL" = "1" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    if rc-service wiz-disk-scanner status | grep -q running; then
      info "wiz-disk-scanner is running, restarting (openrc)"
      rc-service wiz-disk-scanner restart
    else
      rc-service wiz-disk-scanner start
    fi
  fi
}

start_sysvinit_services() {
  if [ "$WIZ_INSTALL_ONLY" = "1" ]; then
    return
  fi

  # wiz-sensor
  if service wiz-sensor status > /dev/null 2>&1; then
    info "wiz-sensor is running, restarting (sysvinit)"
    service wiz-sensor restart
  else
    service wiz-sensor start
  fi

  # wiz-disk-scanner (only if container install and enabled)
  if [ "$CONTAINER_INSTALL" = "1" ] && [ "$WIZ_DISK_SCANNER" = "1" ]; then
    if service wiz-disk-scanner status > /dev/null 2>&1; then
      info "wiz-disk-scanner is running, restarting (sysvinit)"
      service wiz-disk-scanner restart
    else
      service wiz-disk-scanner start
    fi
  fi
}

start_services() {
  if [ "$SERVICE_MANAGER" = "openrc" ]; then
    start_openrc_services
  elif [ "$SERVICE_MANAGER" = "sysvinit" ]; then
    start_sysvinit_services
  elif [ "$SERVICE_MANAGER" = "systemd" ]; then
    start_systemd_services
  fi
}

install_with_container() {
  export WIZ_IMAGE_REGISTRY="${CONTAINER_REGISTRY}"

  create_sensor_env_file
  install_container sensor
  if [ "$WIZ_DISK_SCANNER" = "1" ]; then
    create_disk_scanner_env_file
    install_container disk-scanner
    # -m only applies to the deepest directory, which is intentional
    # shellcheck disable=SC2174
    mkdir -m 700 -p "${SENSOR_HOST_STORE}/wiz-sensor-share" || {
      error "Failed to create directory ${SENSOR_HOST_STORE}/wiz-sensor-share"
      exit 1
    }
    chown 2202:2202 "${SENSOR_HOST_STORE}/wiz-sensor-share" || {
      error "Failed to set ownership on ${SENSOR_HOST_STORE}/wiz-sensor-share"
      exit 1
    }
  fi
}

create_installer_env_file() {
  # global configs for the busybox installer
  INSTALLER_ENV_FILE=${SENSOR_HOST_STORE}/installer.env
  local mount_propagation=""
  if [ "$WIZ_DISK_SCANNER" = "1" ]; then
    mount_propagation=$(get_disk_scanner_mount_propagation)
  fi

  cat << EOF > "$INSTALLER_ENV_FILE"
WIZ_DISK_SCANNER=${WIZ_DISK_SCANNER}
WIZ_DISK_SCANNER_MOUNT_PROPAGATION=${mount_propagation}
EOF
  chown "root:root" "${INSTALLER_ENV_FILE}" || {
    error "Failed to set ownership on ${INSTALLER_ENV_FILE}"
    exit 1
  }
  chmod 400 "${INSTALLER_ENV_FILE}" || {
    error "Failed to set permissions on ${INSTALLER_ENV_FILE}"
    exit 1
  }
}

# sensor_init bind-mounts /etc/resolv.conf once, when it creates the sensor's
# mount namespace, so start the sensor after the network manager writes it.
# Wants= and After= never fail the start, and the wait-online service bounds
# the wait.
configure_network_online_ordering() {
  if [ "$SERVICE_MANAGER" != "systemd" ]; then
    return
  fi

  local dropin_dir="/etc/systemd/system/wiz-sensor.service.d"
  local dropin_file="${dropin_dir}/10-network-online.conf"

  if is_truthy "$WIZ_SKIP_NETWORK_ONLINE_ORDERING"; then
    info "Skipping the network-online ordering because WIZ_SKIP_NETWORK_ONLINE_ORDERING is set"
    rm -f "$dropin_file" || {
      error "Failed to remove ${dropin_file}"
      exit 1
    }
  else
    mkdir -p "$dropin_dir" || {
      error "Failed to create directory ${dropin_dir}"
      exit 1
    }
    cat << EOF > "$dropin_file"
[Unit]
Wants=network-online.target
After=network-online.target nss-lookup.target
EOF
  fi
}

install_without_container() {
  create_sensor_env_file
  create_installer_env_file
  cp "$SENSOR_ENV_FILE" "${SENSOR_HOST_STORE}/engine-downloader.env"
  if [ "$WIZ_DISK_SCANNER" = "1" ]; then
    create_disk_scanner_env_file
    cp "$SENSOR_ENV_FILE" "${DISK_SCANNER_HOST_STORE}/disk-scanner-downloader.env"
  fi
  configure_network_online_ordering

  if is_truthy "$WIZ_PACKAGE_SKIP_INSTALL"; then
    info "Skipping package installation because WIZ_PACKAGE_SKIP_INSTALL is set"
    return
  fi

  if [ -n "$LOCAL_PACKAGE" ]; then
    install_local_package
  else
    install_package
  fi
}

create_legacy_config_if_needed() {
  if [[ "$WIZ_SENSOR_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    IFS='.' read -r -a version_array <<< "$WIZ_SENSOR_VERSION"
    if [ "${version_array[2]}" -le 4413 ]; then
      create_legacy_config_file
    fi
  else
    rm -f "$SENSOR_LEGACY_CONFIG_FILE" || true
  fi
}

check_time() {
  # Skip time check if WIZ_SKIP_TIME_CHECK is set
  if [ "$WIZ_SKIP_TIME_CHECK" = "1" ]; then
    info "Skipping time check"
    return 0
  fi

  # Get current system time in seconds since epoch
  local system_time
  system_time=$(date +%s)

  # The Date: header is CRLF-terminated over the wire; strip the trailing CR.
  local http_time
  if ! http_time=$(curl_proxy -sI "https://$(get_auth_subdomain)" | grep -i "^date:" | cut -d' ' -f2- | tr -d '\r') || [ -z "$http_time" ]; then
    warn "Could not verify system time. Installation will proceed, but please ensure your system time is accurate."
    return 0
  fi

  local internet_time=""
  internet_time=$(date -d "$http_time" +%s 2> /dev/null) \
    || internet_time=$(date -j -f "%a, %d %b %Y %H:%M:%S %Z" "$http_time" +%s 2> /dev/null) \
    || true
  if [ -z "$internet_time" ]; then
    warn "Could not parse internet time. Installation will proceed, but please ensure your system time is accurate."
    return 0
  fi

  # Calculate time difference in minutes
  local time_diff=$(((system_time - internet_time) / 60))
  time_diff=${time_diff#-} # Get absolute value

  if [ "$time_diff" -gt 5 ]; then
    error "System time is off by more than 5 minutes from internet time. Please sync your system time and try again. Internet time: $internet_time, System time: $system_time."
    exit 1
  fi
}

function do_install() {
  set_consts
  print_banner
  check_os_and_distro
  check_databricks
  select_install_method
  config
  check_root
  check_tmp_dir
  check_arch
  check_kernel_version
  ensure_curl_installed

  if is_truthy "$WIZ_PACKAGE_INSTALL_ONLY"; then
    configure_network_online_ordering
    if [ -n "$LOCAL_PACKAGE" ]; then
      install_local_package
    else
      install_package
    fi
    completed "Wiz sensor package was successfully installed (package-only mode)."
    return
  fi

  check_time
  check_arguments
  avoid_reinstall
  create_sensor_dir
  setup_logger
  check_update_policy
  prepare_proxy_cert_file
  check_api_key
  generate_persistent_id
  create_legacy_config_if_needed
  stop_old_components_and_wait
  if [ "$CONTAINER_INSTALL" = "1" ]; then
    install_with_container
  else
    install_without_container
  fi
  enable_services
  start_services
  if wait_for_sensor_to_start; then
    if is_truthy "$WIZ_PACKAGE_SKIP_INSTALL"; then
      completed "Wiz sensor was successfully configured (installation skipped)."
    elif [ "$WIZ_INSTALL_ONLY" = "1" ]; then
      completed "Wiz sensor was successfully installed (install-only mode, service not started)."
    else
      completed "Wiz sensor was successfully installed!"
    fi
  else
    if is_truthy "$WIZ_PACKAGE_SKIP_INSTALL"; then
      warn "Wiz sensor was configured, but the service may not be running correctly."
    else
      warn "Wiz sensor was installed, but the service may not be running correctly."
    fi
  fi
}

set -e
trap on_exit EXIT
do_install
