#!/bin/bash



APP_DIR='/opt/r7-office/organizer'

# R7 [ ORG-1332; retain the ORG-1052 launcher/exec_dir contract.
APP_BIN="${APP_DIR}/r7organizer"
PROFILE_ROOT="${HOME}/.r7organizer"
STATE_DIR="${PROFILE_ROOT}/.r7organizer-wrapper-state"
ATTACHMENT_STAGE_DIR="${PROFILE_ROOT}/.r7organizer-mail-attachments"
STAMP_FILE="${PROFILE_ROOT}/.r7organizer-startupcache.stamp"
LEGACY_SESSION_FILE="${PROFILE_ROOT}/.r7organizer-session-active"
RESET_FLAG=".r7exchange-force-startupcache-reset"
SUPPRESS_FLAG=".r7exchange-skip-startup-login-once"
APP_ARGS=("$@")
SESSION_FILE=""
LOCK_OPEN=0
LOCK_HELD=0
OTHER_SESSION_ACTIVE=0

# These helpers return data in R7_RESULT, without eval or shell re-parsing.
decode_uri_component() {
  local value="$1" char hex decoded
  R7_RESULT=""
  while [ -n "$value" ]; do
    char="${value:0:1}"
    if [ "$char" = '%' ] && [[ "${value:1:2}" =~ ^[0-9A-Fa-f]{2}$ ]]; then
      hex="${value:1:2}"
      [ "$hex" != '00' ] || return 1
      printf -v decoded '%b' "\\x${hex}"
      R7_RESULT+="$decoded"
      value="${value:3}"
    elif [ "$char" = '%' ]; then
      return 1
    else
      R7_RESULT+="$char"
      value="${value:1}"
    fi
  done
}

encode_uri_component() {
  local LC_ALL=C value="$1" char number
  R7_RESULT=""
  while [ -n "$value" ]; do
    char="${value:0:1}"
    case "$char" in
      [a-zA-Z0-9.~_-]) R7_RESULT+="$char" ;;
      *) printf -v number '%%%02X' "'$char"; R7_RESULT+="$number" ;;
    esac
    value="${value:1}"
  done
}

normalize_local_attachment() {
  local value="$1"
  case "${value,,}" in
    file://localhost/*) value="/${value:17}"; decode_uri_component "$value" || return 1; value="$R7_RESULT" ;;
    file:///*) value="/${value:8}"; decode_uri_component "$value" || return 1; value="$R7_RESULT" ;;
    *://*) return 1 ;;
    '~/'*) value="${HOME}/${value:2}" ;;
  esac
  [ -f "$value" ] || return 1
  R7_RESULT="$(readlink -f -- "$value")" || return 1
  [ -n "$R7_RESULT" ] && [ -f "$R7_RESULT" ]
}

private_directory() {
  local directory="$1"
  [ ! -L "$directory" ] || return 1
  (umask 077; mkdir -p -- "$directory") || return 1
  [ -d "$directory" ] && [ -O "$directory" ] || return 1
  chmod 700 -- "$directory"
}

stage_attachment() {
  local original="$1" source directory destination
  normalize_local_attachment "$original" || { R7_RESULT="$original"; return 1; }
  source="$R7_RESULT"
  if [[ "$source" != "${ATTACHMENT_STAGE_DIR}/"* ]]; then
    private_directory "$ATTACHMENT_STAGE_DIR" || { R7_RESULT="$original"; return 1; }
    directory="$(umask 077; mktemp -d "${ATTACHMENT_STAGE_DIR}/part-XXXXXXXX")" || { R7_RESULT="$original"; return 1; }
    destination="${directory}/${source##*/}"
    if ! (umask 077; cp -- "$source" "$destination" && chmod 600 -- "$destination"); then
      rm -f -- "$destination"
      rmdir -- "$directory" 2>/dev/null || true
      R7_RESULT="$original"
      return 1
    fi
    source="$destination"
  fi
  # A file URI keeps commas, percent signs and quotes out of Compose's CSV syntax.
  encode_uri_component "$source"
  R7_RESULT="file://${R7_RESULT//%2F/\/}"
}

join_values() {
  local value
  R7_RESULT=""
  for value in "$@"; do
    [ -n "$value" ] || continue
    [ -z "$R7_RESULT" ] || R7_RESULT+=','
    R7_RESULT+="$value"
  done
}

append_field() {
  local key="$1" value="$2"
  [ -n "$value" ] || return 0
  encode_uri_component "$value"
  FIELDS+=("${key}=${R7_RESULT}")
}

rewrite_attachment_csv() {
  local value="$1" local_only="${2:-0}" part rest candidate tail
  local values=()
  # A single existing filename may itself contain a comma.
  if normalize_local_attachment "$value"; then
    stage_attachment "$value" || true
    return 0
  fi
  rest="$value"
  while :; do
    part="${rest%%,*}"
    # Older xdg-email passes raw absolute paths separated by commas.
    # Recover a comma inside a name by checking the joined path on disk.
    if [[ "$part" == /* ]] && ! normalize_local_attachment "$part"; then
      candidate="$part"
      tail="$rest"
      while [[ "$tail" == *,* ]]; do
        tail="${tail#*,}"
        case "${tail%%,*}" in /*|'~/'*|*://*) break ;; esac
        candidate+=",${tail%%,*}"
        if normalize_local_attachment "$candidate"; then
          part="$candidate"
          rest="$tail"
          break
        fi
      done
    fi
    if [ "$local_only" -eq 0 ] || normalize_local_attachment "$part"; then
      stage_attachment "$part" || true
      values+=("$R7_RESULT")
    fi
    [[ "$rest" == *,* ]] || break
    rest="${rest#*,}"
  done
  join_values "${values[@]}"
}

rewrite_compose_fields() {
  local value="$1" extra="${2:-}" field="" quote="" char next previous="" key attachment in_attachments=0
  local fields=() output=() attachments=()
  while [ -n "$value" ]; do
    char="${value:0:1}"; next="${value:1:1}"
    if [ -n "$quote" ] && [ "$char" = "$quote" ] && { [ "$next" = ',' ] || [ -z "$next" ]; }; then
      quote=""
    elif [ -z "$quote" ] && [ "$previous" = '=' ] && { [ "$char" = "'" ] || [ "$char" = '"' ]; }; then
      quote="$char"
    elif [ "$char" = ',' ] && [ -z "$quote" ]; then
      fields+=("$field"); field=""; previous=""; value="${value:1}"; continue
    fi
    field+="$char"; previous="$char"; value="${value:1}"
  done
  fields+=("$field")
  for field in "${fields[@]}"; do
    key="${field%%=*}"
    if [[ "$field" == *=* ]] && { [ "$key" = 'attachment' ] || [ "$key" = 'attach' ]; }; then
      attachment="${field#*=}"
      if { [[ "$attachment" == \'*\' ]] || [[ "$attachment" == \"*\" ]]; } && [ "${#attachment}" -ge 2 ]; then
        attachment="${attachment:1:${#attachment}-2}"
      elif ! normalize_local_attachment "$attachment" && decode_uri_component "$attachment"; then
        attachment="$R7_RESULT"
      fi
      rewrite_attachment_csv "$attachment"
      attachments+=("$R7_RESULT")
      in_attachments=1
    elif [ "$in_attachments" -eq 1 ] && [[ ! "$field" =~ ^[a-zA-Z][a-zA-Z0-9_-]*= ]] &&
        stage_attachment "$field"; then
      # An unquoted native attachment list has bare paths after its first entry.
      attachments+=("$R7_RESULT")
    else
      in_attachments=0
      [ -z "$field" ] || output+=("$field")
    fi
  done
  # Compose reads only one value for a repeated key.
  join_values "${attachments[@]}" "$extra"
  if [ -n "$R7_RESULT" ]; then
    encode_uri_component "$R7_RESULT"
    output+=("attachment=${R7_RESULT}")
  fi
  join_values "${output[@]}"
}

native_option_takes_value() {
  case "$1" in
    -profile|--profile|-P|-p|-file|--file|-url|--url|-chrome|--chrome|-compose|--compose|-remote|--remote) return 0 ;;
  esac
  return 1
}

rewrite_native_compose() {
  local i=0 mode="" position=-1 value="" arg inner attachment
  local rebuilt=() extra=() staged=()
  while [ "$i" -lt "${#APP_ARGS[@]}" ]; do
    arg="${APP_ARGS[$i]}"
    case "$arg" in
      --attach|--attachment)
        [ $((i+1)) -lt "${#APP_ARGS[@]}" ] || return 1
        i=$((i+1)); extra+=("${APP_ARGS[$i]}") ;;
      --attach=*|--attachment=*) extra+=("${arg#*=}") ;;
      -compose|--compose)
        mode='compose'; rebuilt+=("$arg"); position="${#rebuilt[@]}"; value=""
        if [ $((i+1)) -lt "${#APP_ARGS[@]}" ] && [[ "${APP_ARGS[$((i+1))]}" != -* ]]; then
          if ! normalize_local_attachment "${APP_ARGS[$((i+1))]}"; then
            i=$((i+1)); value="${APP_ARGS[$i]}"
          fi
        fi
        rebuilt+=("$value") ;;
      -remote|--remote)
        rebuilt+=("$arg")
        if [ $((i+1)) -lt "${#APP_ARGS[@]}" ]; then
          i=$((i+1)); value="${APP_ARGS[$i]}"
          if [[ "$value" == 'xfeDoCommand(composeMessage)' ]] || [[ "$value" == 'xfeDoCommand(composeMessage,'*')' ]]; then
            mode='remote'; position="${#rebuilt[@]}"
          fi
          rebuilt+=("$value")
        fi ;;
      *)
        if native_option_takes_value "$arg"; then
          rebuilt+=("$arg")
          if [ $((i+1)) -lt "${#APP_ARGS[@]}" ] && [[ "${APP_ARGS[$((i+1))]}" != -* ]]; then
            i=$((i+1)); rebuilt+=("${APP_ARGS[$i]}")
          fi
        elif [[ "$arg" != -* ]] && [ -n "$mode" ] && normalize_local_attachment "$arg"; then
          extra+=("$arg")
        else
          rebuilt+=("$arg")
        fi ;;
    esac
    i=$((i+1))
  done
  [ "$position" -ge 0 ] || return 1
  value="${rebuilt[$position]}"
  if [ "$mode" = 'remote' ]; then
    inner="${value#xfeDoCommand(composeMessage}"
    inner="${inner%)}"; inner="${inner#,}"
  else
    inner="$value"
  fi
  if [[ "${inner,,}" == mailto:* ]]; then
    local TO_VALUES=() CC_VALUES=() BCC_VALUES=() ATTACHMENTS=() FIELDS=()
    parse_mailto "$inner" || return 1
    ATTACHMENTS+=("${extra[@]}")
    [ "${#ATTACHMENTS[@]}" -gt 0 ] || return 0
    compose_mailto_fields || return 1
    inner="$R7_RESULT"
  else
    if [ -z "$inner" ] && [ "${#extra[@]}" -eq 0 ]; then return 0; fi
    for attachment in "${extra[@]}"; do
      rewrite_attachment_csv "$attachment"
      staged+=("$R7_RESULT")
    done
    join_values "${staged[@]}"; attachment="$R7_RESULT"
    rewrite_compose_fields "$inner" "$attachment"; inner="$R7_RESULT"
  fi
  if [ "$mode" = 'remote' ]; then inner="xfeDoCommand(composeMessage${inner:+,${inner}})"; fi
  rebuilt[$position]="$inner"
  APP_ARGS=("${rebuilt[@]}")
}

parse_mailto() {
  local value="${1:7}" query="" pair key
  if [[ "$value" == *'?'* ]]; then query="${value#*\?}"; value="${value%%\?*}"; fi
  decode_uri_component "$value" || return 1
  [ -z "$R7_RESULT" ] || TO_VALUES+=("$R7_RESULT")
  while [ -n "$query" ]; do
    pair="${query%%&*}"; key="${pair%%=*}"; value="${pair#*=}"
    [ "$pair" != "$key" ] || value=""
    decode_uri_component "$value" || return 1
    value="$R7_RESULT"
    case "${key,,}" in
      to) TO_VALUES+=("$value") ;;
      cc) CC_VALUES+=("$value") ;;
      bcc) BCC_VALUES+=("$value") ;;
      attach|attachment) ATTACHMENTS+=("$value") ;;
      subject|body) append_field "${key,,}" "$value" ;;
    esac
    [[ "$query" == *'&'* ]] || break
    query="${query#*&}"
  done
}

translate_xdg_args() {
  local arg value detected=0 i=0 mailto_seen=0 local_file_seen=0
  local TO_VALUES=() CC_VALUES=() BCC_VALUES=() ATTACHMENTS=() FIELDS=() pass=() files=()
  for arg in "${APP_ARGS[@]}"; do
    case "${arg,,}" in
      --attach|--attachment|--attach=*|--attachment=*|--subject|--subject=*|--body|--body=*|--cc|--cc=*|--bcc|--bcc=*|--utf8) detected=1 ;;
      mailto:*\?attach=*|mailto:*\&attach=*|mailto:*\?attachment=*|mailto:*\&attachment=*) detected=1 ;;
    esac
    if [[ "${arg,,}" == mailto:* ]]; then mailto_seen=1
    elif normalize_local_attachment "$arg"; then local_file_seen=1; fi
  done
  if [ "$mailto_seen" -eq 1 ] && [ "$local_file_seen" -eq 1 ]; then detected=1; fi
  [ "$detected" -eq 1 ] || return 1
  while [ "$i" -lt "${#APP_ARGS[@]}" ]; do
    arg="${APP_ARGS[$i]}"
    case "$arg" in
      --attach|--attachment|--subject|--body|--cc|--bcc)
        [ $((i+1)) -lt "${#APP_ARGS[@]}" ] || return 1
        i=$((i+1)); value="${APP_ARGS[$i]}"
        case "$arg" in
          --attach|--attachment) ATTACHMENTS+=("$value") ;;
          --cc) CC_VALUES+=("$value") ;;
          --bcc) BCC_VALUES+=("$value") ;;
          *) append_field "${arg#--}" "$value" ;;
        esac ;;
      --attach=*|--attachment=*) ATTACHMENTS+=("${arg#*=}") ;;
      --subject=*|--body=*) value="${arg%%=*}"; append_field "${value#--}" "${arg#*=}" ;;
      --cc=*) CC_VALUES+=("${arg#*=}") ;;
      --bcc=*) BCC_VALUES+=("${arg#*=}") ;;
      --utf8) ;;
      -*)
        pass+=("$arg")
        if [ $((i+1)) -lt "${#APP_ARGS[@]}" ] && [[ "${APP_ARGS[$((i+1))]}" != -* ]]; then
          i=$((i+1)); pass+=("${APP_ARGS[$i]}")
        fi ;;
      *)
        if [[ "${arg,,}" == mailto:* ]]; then parse_mailto "$arg" || return 1
        elif normalize_local_attachment "$arg"; then ATTACHMENTS+=("$arg")
        else TO_VALUES+=("$arg"); fi ;;
    esac
    i=$((i+1))
  done
  compose_mailto_fields || return 1
  APP_ARGS=("${pass[@]}" -compose "$R7_RESULT")
}

compose_mailto_fields() {
  local value
  local files=()
  join_values "${TO_VALUES[@]}"; append_field to "$R7_RESULT"
  join_values "${CC_VALUES[@]}"; append_field cc "$R7_RESULT"
  join_values "${BCC_VALUES[@]}"; append_field bcc "$R7_RESULT"
  for value in "${ATTACHMENTS[@]}"; do
    rewrite_attachment_csv "$value" 1
    [ -z "$R7_RESULT" ] || files+=("$R7_RESULT")
  done
  join_values "${files[@]}"; append_field attachment "$R7_RESULT"
  [ "${#FIELDS[@]}" -gt 0 ] || return 1
  join_values "${FIELDS[@]}"
}

profile_directory() {
  local path="$1"
  [ -d "$path" ] && [ -f "${path}/prefs.js" ] || return 0
  path="$(cd -- "$path" && pwd -P)" || return 0
  [ "$path" != '/' ] && [ "$path" != "$HOME" ] || return 0
  printf '%s\n' "$path"
}

collect_profile_directories() {
  local line path="" relative=1 i=0
  if [ -f "${PROFILE_ROOT}/profiles.ini" ]; then
    while IFS= read -r line || [ -n "$line" ]; do
      line="${line%$'\r'}"
      case "$line" in
        \[*)
          if [ -n "$path" ]; then [ "$relative" = 1 ] && profile_directory "${PROFILE_ROOT}/${path}" || profile_directory "$path"; fi
          path=""; relative=1 ;;
        Path=*) path="${line#Path=}" ;;
        IsRelative=*) relative="${line#IsRelative=}" ;;
      esac
    done < "${PROFILE_ROOT}/profiles.ini"
    if [ -n "$path" ]; then [ "$relative" = 1 ] && profile_directory "${PROFILE_ROOT}/${path}" || profile_directory "$path"; fi
  fi
  for path in "${PROFILE_ROOT}"/*; do profile_directory "$path"; done
  while [ "$i" -lt "${#APP_ARGS[@]}" ]; do
    case "${APP_ARGS[$i]}" in
      -profile|--profile) i=$((i+1)); profile_directory "${APP_ARGS[$i]:-}" ;;
      -profile=*|--profile=*) profile_directory "${APP_ARGS[$i]#*=}" ;;
    esac
    i=$((i+1))
  done
}

runtime_stamp() {
  local file inputs=()
  for file in "${APP_DIR}/omni.ja" "${APP_DIR}/chrome/"*.jar "${APP_DIR}/chrome/"*.ja "${APP_DIR}/"*.xpi; do
    [ ! -f "$file" ] || inputs+=("$file")
  done
  [ "${#inputs[@]}" -gt 0 ] || return 1
  (set -o pipefail; sha256sum -- "${inputs[@]}" 2>/dev/null | sha256sum | awk '{print $1}')
}

write_private_file() {
  local destination="$1" value="$2" temporary
  [ ! -L "$destination" ] || return 1
  temporary="$(umask 077; mktemp "${STATE_DIR}/write-XXXXXXXX")" || return 1
  printf '%s\n' "$value" > "$temporary" && mv -f -- "$temporary" "$destination"
}

session_pid() {
  local file="$1" line
  R7_RESULT=""
  [ -f "$file" ] && [ ! -L "$file" ] || return 1
  IFS= read -r line < "$file" || return 1
  line="${line#pid=}"
  [[ "$line" =~ ^[1-9][0-9]*$ ]] || return 1
  R7_RESULT="$line"
}

maintain_startup_cache() {
  local file profile cache current previous="" unclean=0 force=0 completed=1 cleared=1
  local dead_sessions=()
  OTHER_SESSION_ACTIVE=0
  for file in "${STATE_DIR}/"session-* "$LEGACY_SESSION_FILE"; do
    [ "$file" != "$SESSION_FILE" ] || continue
    [ -f "$file" ] || continue
    if session_pid "$file" && kill -0 "$R7_RESULT" 2>/dev/null; then
      OTHER_SESSION_ACTIVE=1
    else
      dead_sessions+=("$file"); unclean=1
    fi
  done
  [ "$OTHER_SESSION_ACTIVE" -eq 0 ] || return 0
  current="$(runtime_stamp)" || return 0
  [ ! -f "$STAMP_FILE" ] || IFS= read -r previous < "$STAMP_FILE" || true
  while IFS= read -r profile; do
    force=0; [ ! -f "${profile}/${RESET_FLAG}" ] || force=1
    if [ "$current" != "$previous" ] || [ "$unclean" -eq 1 ] || [ "$force" -eq 1 ]; then
      cache="${profile}/startupCache"
      cleared=1
      # Never follow a cache symlink or delete a profile directory itself.
      if [ -e "$cache" ] || [ -L "$cache" ]; then
        if [ -d "$cache" ] && [ ! -L "$cache" ] && [ "$(readlink -f -- "$cache")" = "$cache" ]; then
          rm -rf -- "$cache" || cleared=0
        else
          cleared=0
        fi
      fi
      if [ "$unclean" -eq 1 ] || [ "$force" -eq 1 ]; then
        write_private_file "${profile}/${SUPPRESS_FLAG}" '{"reason":"wrapper-cache-recovery"}' || true
      fi
      if [ "$cleared" -eq 1 ]; then
        [ -L "${profile}/${RESET_FLAG}" ] || rm -f -- "${profile}/${RESET_FLAG}"
      else
        completed=0
      fi
    fi
  done < <(collect_profile_directories | sort -u)
  for file in "${dead_sessions[@]}"; do [ -L "$file" ] || rm -f -- "$file"; done
  if [ "$completed" -eq 1 ]; then write_private_file "$STAMP_FILE" "$current" || true; fi
  # Compose also removes staged files after send/discard. Keep recent copies.
  if [ -d "$ATTACHMENT_STAGE_DIR" ] && [ ! -L "$ATTACHMENT_STAGE_DIR" ] && [ -O "$ATTACHMENT_STAGE_DIR" ]; then
    find "$ATTACHMENT_STAGE_DIR" -mindepth 1 -maxdepth 2 -type f -mtime +2 -delete 2>/dev/null || true
    find "$ATTACHMENT_STAGE_DIR" -mindepth 1 -maxdepth 1 -type d -empty -mtime +2 -delete 2>/dev/null || true
  fi
}

forward_signal() {
  kill -s "$1" "$APP_PID" 2>/dev/null || true
}

if [ ! -x "$APP_BIN" ]; then printf 'Organizer executable is not available: %s\n' "$APP_BIN" >&2; exit 127; fi
export LD_LIBRARY_PATH="$APP_DIR"
# System-provided URLs must keep the normal mailto security checks.
has_osint=0
for arg in "${APP_ARGS[@]}"; do
  case "${arg,,}" in -osint|--osint) has_osint=1 ;; esac
done
if [ "$has_osint" -eq 0 ] && ! rewrite_native_compose; then
  translate_xdg_args || true
fi

if private_directory "$STATE_DIR"; then
  SESSION_FILE="$(umask 077; mktemp "${STATE_DIR}/session-XXXXXXXX")" || SESSION_FILE=""
  [ -z "$SESSION_FILE" ] || write_private_file "$SESSION_FILE" "pid=$$" || SESSION_FILE=""
  if command -v flock >/dev/null 2>&1 && [ ! -L "${STATE_DIR}/launch.lock" ]; then
    if { exec 9>>"${STATE_DIR}/launch.lock"; }; then
      LOCK_OPEN=1
      if flock -w 2 9; then LOCK_HELD=1; maintain_startup_cache; fi
    fi
  fi
fi
(
  # Background jobs otherwise inherit ignored INT/QUIT from noninteractive bash.
  trap - INT QUIT
  exec "$APP_BIN" "${APP_ARGS[@]}"
) 9>&- &
APP_PID=$!
[ -z "$SESSION_FILE" ] || write_private_file "$SESSION_FILE" "pid=$APP_PID" || true
if [ "$LOCK_HELD" -eq 1 ]; then flock -u 9; fi
if [ "$LOCK_OPEN" -eq 1 ]; then exec 9>&-; fi
trap 'forward_signal TERM' TERM
trap 'forward_signal INT' INT
trap 'forward_signal HUP' HUP
wait "$APP_PID"
APP_STATUS=$?
# A signal can interrupt wait before the child has actually exited.
while kill -0 "$APP_PID" 2>/dev/null; do wait "$APP_PID"; APP_STATUS=$?; done
if [ "$APP_STATUS" -eq 0 ] && [ -n "$SESSION_FILE" ]; then rm -f -- "$SESSION_FILE"; fi
exit "$APP_STATUS"
# R7 ]
