#!/usr/bin/env bash

# HCL Sametime Docker mitigation helper for CVE-2026-114938 (Java4Shell)
# Version 1.1, 2026-11-24

set -Eeuo pipefail

readonly MITIGATION_OPTION='-XX:-UseBASE64Intrinsics'

install_dir='/opt/hcl/sametime'
recreate=false
dry_run=false
committed=false
files_changed=false
backup_env=''
backup_compose=''

usage() {
  cat <<'EOF'
Usage:
  mitigate-java4shell-docker.sh [--directory PATH] [--dry-run | --recreate]

Options:
  --directory PATH  Sametime installation directory
                    (default: /opt/hcl/sametime)
  --dry-run         Check and report intended changes without modifying files
  --recreate        Recreate all Compose containers if this run changes files
  -h, --help        Show this help

Without --recreate, the script patches and validates the configuration but
does not restart or recreate containers.
EOF
}

log() {
  printf '[java4shell] %s\n' "$*"
}

die() {
  printf '[java4shell] ERROR: %s\n' "$*" >&2
  exit 1
}

while (($# > 0)); do
  case "$1" in
    --directory)
      (($# >= 2)) || die '--directory requires a path'
      install_dir=$2
      shift 2
      ;;
    --recreate)
      recreate=true
      shift
      ;;
    --dry-run)
      dry_run=true
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "unknown argument: $1"
      ;;
  esac
done

if [[ "$dry_run" == true && "$recreate" == true ]]; then
  die '--dry-run and --recreate cannot be used together'
fi

[[ -d "$install_dir" ]] || die "directory not found: $install_dir"

env_file="$install_dir/custom.env"
compose_file="$install_dir/docker-compose.yml"

[[ -f "$env_file" ]] || die "file not found: $env_file"
[[ -f "$compose_file" ]] || die "file not found: $compose_file"
[[ -w "$env_file" ]] || die "file is not writable: $env_file"
[[ -w "$compose_file" ]] || die "file is not writable: $compose_file"
command -v docker >/dev/null 2>&1 || die 'docker command not found'
docker compose version >/dev/null 2>&1 || die 'docker compose is unavailable'

active_env_count=$(grep -Ec '^[[:space:]]*JAVA_TOOL_OPTIONS=' "$env_file" || true)
((active_env_count <= 1)) || die 'custom.env contains multiple active JAVA_TOOL_OPTIONS entries'

compose_java_count=$(grep -Ec '^[[:space:]]*-[[:space:]]*JAVA_TOOL_OPTIONS=' "$compose_file" || true)
((compose_java_count == 1)) || die "expected exactly one list-style JAVA_TOOL_OPTIONS entry in docker-compose.yml, found $compose_java_count"

if [[ "$dry_run" == true ]]; then
  log 'DRY RUN: no files will be changed and no containers will be recreated.'

  if ((active_env_count == 0)); then
    log "Would add JAVA_TOOL_OPTIONS=$MITIGATION_OPTION to custom.env."
  elif grep -Eq "^[[:space:]]*JAVA_TOOL_OPTIONS=.*${MITIGATION_OPTION}" "$env_file"; then
    log 'custom.env already contains the mitigation option; no change needed.'
  else
    log "Would append $MITIGATION_OPTION to the existing JAVA_TOOL_OPTIONS in custom.env."
  fi

  if grep -Eq "^[[:space:]]*-[[:space:]]*JAVA_TOOL_OPTIONS=.*${MITIGATION_OPTION}" "$compose_file"; then
    log 'The Compose JAVA_TOOL_OPTIONS already contain the mitigation option; no change needed.'
  else
    log "Would append $MITIGATION_OPTION to the Compose JAVA_TOOL_OPTIONS."
  fi

  log 'Validating the current Compose configuration...'
  (
    cd "$install_dir"
    docker compose config --quiet
  )
  log 'DRY RUN completed successfully; no changes were made.'
  exit 0
fi

rollback_on_failure() {
  local exit_code=$?

  if ((exit_code != 0)) && [[ "$committed" != true ]]; then
    log 'An error occurred before validation completed; restoring backups.'
    [[ -n "$backup_env" && -f "$backup_env" ]] && cp -p -- "$backup_env" "$env_file"
    [[ -n "$backup_compose" && -f "$backup_compose" ]] && cp -p -- "$backup_compose" "$compose_file"
  fi
}
trap rollback_on_failure EXIT

timestamp=$(date '+%Y%m%d-%H%M%S')
backup_env="${env_file}.bak-java4shell-${timestamp}"
backup_compose="${compose_file}.bak-java4shell-${timestamp}"

cp -p -- "$env_file" "$backup_env"
cp -p -- "$compose_file" "$backup_compose"
log "Backups created: $backup_env and $backup_compose"

env_tmp=$(mktemp "${env_file}.tmp.XXXXXX")
if ((active_env_count == 0)); then
  awk -v option="$MITIGATION_OPTION" '
    { lines[NR] = $0 }
    END {
      for (i = 1; i <= NR; i++) print lines[i]
      if (NR > 0 && lines[NR] != "") print ""
      print "JAVA_TOOL_OPTIONS=" option
    }
  ' "$env_file" >"$env_tmp"
else
  awk -v option="$MITIGATION_OPTION" '
    /^[[:space:]]*JAVA_TOOL_OPTIONS=/ && index($0, option) == 0 {
      $0 = $0 " " option
    }
    { print }
  ' "$env_file" >"$env_tmp"
fi
chmod --reference="$env_file" "$env_tmp"
if cmp -s -- "$env_tmp" "$env_file"; then
  rm -f -- "$env_tmp"
  log 'custom.env already contains the mitigation option; no change needed.'
else
  mv -- "$env_tmp" "$env_file"
  files_changed=true
  log 'Added the mitigation option to custom.env.'
fi

compose_tmp=$(mktemp "${compose_file}.tmp.XXXXXX")
awk -v option="$MITIGATION_OPTION" '
  /^[[:space:]]*-[[:space:]]*JAVA_TOOL_OPTIONS=/ {
    if (index($0, option) == 0) $0 = $0 " " option
  }
  { print }
' "$compose_file" >"$compose_tmp"

chmod --reference="$compose_file" "$compose_tmp"
if cmp -s -- "$compose_tmp" "$compose_file"; then
  rm -f -- "$compose_tmp"
  log 'The proxy service already contains the mitigation option; no change needed.'
else
  mv -- "$compose_tmp" "$compose_file"
  files_changed=true
  log 'Added the mitigation option to the proxy service.'
fi

log 'Validating the Compose configuration...'
(
  cd "$install_dir"
  docker compose config --quiet
)
committed=true
log 'Compose validation succeeded.'

log 'Effective JAVA_TOOL_OPTIONS entries:'
(
  cd "$install_dir"
  docker compose config | grep 'JAVA_TOOL_OPTIONS' || true
)

if [[ "$recreate" == true && "$files_changed" == true ]]; then
  log 'Recreating the Compose containers...'
  (
    cd "$install_dir"
    docker compose up -d --force-recreate
    docker compose ps
  )
  log 'Containers were recreated. Check application health and logs now.'
elif [[ "$recreate" == true ]]; then
  log 'No configuration changes were necessary; skipping container recreation.'
elif [[ "$files_changed" == true ]]; then
  log 'Configuration updated. Containers have NOT been recreated.'
  log "To activate the change later, run in '$install_dir': docker compose up -d --force-recreate"
else
  log 'No configuration changes were necessary; nothing else was done.'
fi

