#!/usr/bin/env bash
#=============================================================================
# updatealarm.sh - deploy alarm definition files from fullalarm.tar.gz
#
# Stages: 0 precheck | 1 download | 2 extract | 3 backup | 4 install | 5 commit
#
# An EXIT trap rolls back any failure: targets already written are restored
# from .ubak, newly created targets are removed, orphaned .ubak are cleaned.
# Success and non-download failures remove /tmp/fullalarm; a download failure
# keeps the partial file and its version tag so the next run can resume.
#
# Exit codes: 0 ok | 1 download | 2 extract/package | 3 backup
#             4 install | 5 precheck | 6 incomplete rollback
#=============================================================================

#--------------------------- Configuration ------------------------------------
# Paths and thresholds are overridable via FULLALARM_* env vars for testing.
URL="${FULLALARM_URL:-http://qa.frps.lnxall.com:5011/dev_public/ems_alarm/alarminfo/fullalarm.tar.gz}"
DL_DIR="${FULLALARM_DL_DIR:-/tmp/fullalarm}"
LNXALL_BASE="${FULLALARM_LNXALL_BASE:-/opt/lnxall_app/app/global/alarminfo}"
ELECT_BASE="${FULLALARM_ELECT_BASE:-/opt/elect_resources/resources/app/conf}"
WGET_RETRY="${FULLALARM_WGET_RETRY:-10}"
WGET_TIMEOUT="${FULLALARM_WGET_TIMEOUT:-30}"
MIN_DISK_KB="${FULLALARM_MIN_DISK_KB:-102400}"
MIN_MEM_KB="${FULLALARM_MIN_MEM_KB:-51200}"

DL_FILE="$DL_DIR/fullalarm.tar.gz"
EXTRACT_DIR="$DL_DIR/extracted"
VERSION_FILE="$DL_DIR/.remote_version"

# Package layout differs from deployment layout; map by language and filename.
SRC_PATTERNS=(
  "*/zh_CN/alarm_def.json"
  "*/en_US/alarm_def.json"
  "*/alarm_zh.json"
  "*/alarm_en.json"
)
DST_PATHS=(
  "$LNXALL_BASE/zh_CN/alarm_def.json"
  "$LNXALL_BASE/en_US/alarm_def.json"
  "$ELECT_BASE/alarm_zh.json"
  "$ELECT_BASE/alarm_en.json"
)

#--------------------------- Runtime state -------------------------------------
# State is reset in main() and per stage so a sourced/reused shell cannot
# carry flags from one run into the next.
SRC_FILES=()
BACKED_UP=()
INSTALLED=()      # includes partially written targets; rollback must cover them
ROLLED_BACK=0
ROLLBACK_FAILED=0 # escalates the exit code to 6
DOWNLOAD_ACTIVE=0 # a failure here must keep the partial file

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [INFO ] $*"; }
err() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [ERROR] $*" >&2; }

exists() {  # [[ -e ]] is false for dangling symlinks; they must still count
  [[ -e "$1" || -L "$1" ]]
}

in_array() {
  local e="$1" a; shift
  for a in "$@"; do [[ "$a" == "$e" ]] && return 0; done
  return 1
}

to_human_kb() {  # integer-only K/M/G formatting, no external dependency
  local kb="$1"
  if (( kb >= 1048576 )); then
    printf '%d.%dG' $(( kb / 1048576 )) $(( kb % 1048576 * 10 / 1048576 ))
  elif (( kb >= 1024 )); then
    printf '%dM' $(( kb / 1024 ))
  else
    printf '%dK' "$kb"
  fi
}

die() {  # exits so the EXIT trap performs the rollback
  err "$2"
  exit "$1"
}

# HEAD metadata is not a content hash: it only answers "can this partial file
# still be resumed?". Any doubt must make the caller re-download from scratch.
get_remote_tag() {
  local hdr etag lm len
  hdr=$(LC_ALL=C wget --spider -S -o - -t 2 -T "$WGET_TIMEOUT" "$URL" 2>/dev/null) || return 1
  etag=$(printf '%s\n' "$hdr" | sed -n 's/^[[:space:]]*ETag:[[:space:]]*//p' | tail -1 | tr -d '\r')
  lm=$(printf '%s\n' "$hdr" | sed -n 's/^[[:space:]]*Last-Modified:[[:space:]]*//p' | tail -1 | tr -d '\r')
  len=$(printf '%s\n' "$hdr" | sed -n 's/^[[:space:]]*Content-Length:[[:space:]]*//p' | tail -1 | tr -d '\r')
  [[ -n "$etag$lm$len" ]] || return 1
  printf '%s|%s|%s' "$etag" "$lm" "$len"
}

#--------------------------- Rollback and cleanup -----------------------------
rollback() {
  (( ROLLED_BACK )) && return 0
  ROLLED_BACK=1
  # Before stage 3 no target file was touched; skip the rollback chatter.
  if (( ${#INSTALLED[@]} == 0 && ${#BACKED_UP[@]} == 0 )); then
    log "  无需回退: 尚未触碰任何目标文件"
    return 0
  fi
  log "开始回退..."

  local dst
  # 1) Written targets: restore from .ubak, or remove if newly created.
  #    A failed restore keeps .ubak as the manual recovery handle.
  for dst in "${INSTALLED[@]}"; do
    if [[ -f "$dst.ubak" ]]; then
      if rm -f "$dst" && mv -f "$dst.ubak" "$dst"; then
        log "  已恢复原文件: $dst"
      else
        err "  恢复失败, 备份保留: $dst.ubak"
        ROLLBACK_FAILED=1
      fi
    elif exists "$dst"; then
      if rm -f "$dst"; then
        log "  已删除新增文件: $dst"
      else
        err "  删除新增文件失败: $dst"
        ROLLBACK_FAILED=1
      fi
    fi
  done

  # 2) Backed up but never written: the original is untouched, drop .ubak.
  for dst in "${BACKED_UP[@]}"; do
    if [[ -f "$dst.ubak" ]] && ! in_array "$dst" "${INSTALLED[@]}"; then
      if rm -f "$dst.ubak"; then
        log "  已清理备份: $dst.ubak"
      else
        err "  清理备份失败(业务文件未受影响): $dst.ubak"
      fi
    fi
  done

  if (( ROLLBACK_FAILED )); then
    err "回退未完全成功, 请人工检查上述失败项(.ubak 已保留)"
  else
    log "回退完成, 系统保持更新前状态"
  fi
}

cleanup_download() {
  [[ -d "$DL_DIR" ]] || return 0
  if rm -rf "$DL_DIR"; then
    log "已清理下载目录: $DL_DIR"
  else
    err "清理下载目录失败: $DL_DIR"
  fi
}

preserve_partial() {
  # Keep the partial file and its tag, drop only extraction leftovers. The next
  # run re-checks the tag via HEAD, so a stale partial can never be appended
  # to a newly published package.
  rm -rf "$EXTRACT_DIR" 2>/dev/null || err "清理解压目录失败: $EXTRACT_DIR"
  log "保留半成品供下次续传: $DL_FILE (版本标记: $VERSION_FILE)"
}

on_exit() {
  local rc=$?
  trap - EXIT INT TERM
  if (( rc != 0 )); then
    err "流程失败(退出码 $rc), 执行回退与清理"
    rollback
    # Escalate so callers can tell a clean failure from one needing manual repair.
    if (( ROLLBACK_FAILED )) && (( rc < 6 )); then
      err "回退不完整, 退出码升级为 6(需人工检查)"
      rc=6
    fi
  fi
  # Stage 1 failures keep the partial; everything else follows req. 5 / req. 6.
  if (( DOWNLOAD_ACTIVE )) && (( rc != 0 )); then
    preserve_partial
  else
    cleanup_download
  fi
  exit "$rc"
}
# Signals become exits so the EXIT trap always performs the rollback.
trap 'exit 130' INT
trap 'exit 143' TERM
trap on_exit EXIT

#--------------------------- Stage 0: precheck ---------------------------------
stage0_precheck() {
  log "Stage 0: 预检"

  if [[ "${FULLALARM_SKIP_ROOT_CHECK:-0}" != "1" ]]; then
    (( EUID == 0 )) || die 5 "需要 root 权限运行 (目标文件位于 /opt 下)"
  fi

  # Reject bad config before any cleanup action can hit an unintended path.
  [[ -n "$DL_DIR" && "$DL_DIR" != "/" ]]             || die 5 "配置错误: 下载目录非法: '$DL_DIR'"
  [[ -n "$LNXALL_BASE" && "$LNXALL_BASE" != "/" ]]   || die 5 "配置错误: LNXALL_BASE 非法: '$LNXALL_BASE'"
  [[ -n "$ELECT_BASE" && "$ELECT_BASE" != "/" ]]     || die 5 "配置错误: ELECT_BASE 非法: '$ELECT_BASE'"
  [[ "$MIN_DISK_KB" =~ ^[0-9]{1,15}$ ]]              || die 5 "配置错误: 磁盘余量阈值非法: '$MIN_DISK_KB'"
  [[ "$MIN_MEM_KB" =~ ^[0-9]{1,15}$ ]]               || die 5 "配置错误: 内存余量阈值非法: '$MIN_MEM_KB'"
  # 10# forces decimal: "0100" would otherwise be octal 64; the 15-digit cap
  # prevents arithmetic expansion overflow.
  MIN_DISK_KB=$(( 10#$MIN_DISK_KB ))
  MIN_MEM_KB=$(( 10#$MIN_MEM_KB ))

  # Check resources before touching a target: extraction can fill the disk
  # mid-way and truncate an alarm file.
  local disk_kb mem_kb
  disk_kb=$(LC_ALL=C df -Pk / 2>/dev/null | awk 'NR==2 {print $4}')
  [[ "$disk_kb" =~ ^[0-9]+$ ]] || die 5 "无法读取根文件系统剩余空间: df -Pk /"
  (( disk_kb > MIN_DISK_KB )) \
    || die 5 "根文件系统剩余空间不足: 可用 $(to_human_kb "$disk_kb") <= 要求 $(to_human_kb "$MIN_DISK_KB")"
  log "  根文件系统可用空间: $(to_human_kb "$disk_kb") (要求 > $(to_human_kb "$MIN_DISK_KB"))"

  # MemAvailable includes reclaimable page cache; fall back to MemFree on
  # kernels older than 3.14 where the field does not exist.
  mem_kb=$(awk '/^MemAvailable:/ {print $2}' /proc/meminfo 2>/dev/null)
  [[ -n "$mem_kb" ]] || mem_kb=$(awk '/^MemFree:/ {print $2}' /proc/meminfo 2>/dev/null)
  [[ "$mem_kb" =~ ^[0-9]+$ ]] || die 5 "无法读取可用内存: /proc/meminfo"
  (( mem_kb > MIN_MEM_KB )) \
    || die 5 "可用内存不足: $(to_human_kb "$mem_kb") <= 要求 $(to_human_kb "$MIN_MEM_KB")"
  log "  可用内存: $(to_human_kb "$mem_kb") (要求 > $(to_human_kb "$MIN_MEM_KB"))"

  # /tmp is world-writable: a symlinked download dir makes rm -rf and tar act
  # outside it. Use "|| die" rather than "&& die": as the function's last
  # command, "[[ -L ... ]] && die" returns 1 when the path is NOT a link,
  # which the EXIT trap would misread as "stage failed (rc 1)".
  [[ ! -L "$DL_DIR" ]] || die 5 "安全: 下载目录是符号链接, 拒绝使用: $DL_DIR"
}

#--------------------------- Stage 1: download ---------------------------------
stage1_download() {
  log "Stage 1: 下载 (版本校验 + 条件续传, 重试 ${WGET_RETRY} 次, 超时 ${WGET_TIMEOUT}s)"
  DOWNLOAD_ACTIVE=1
  mkdir -p "$DL_DIR" || die 1 "无法创建下载目录: $DL_DIR"

  # Compare the HEAD tag with the tag saved for the partial file: match ->
  # resume with -c; mismatch/missing -> delete and download from scratch.
  # wget -c sends no If-Range, so without this check a changed server file
  # could be spliced onto an old partial, or 416-silently reuse an old one.
  local remote_tag
  if remote_tag=$(get_remote_tag); then
    # /tmp is world-writable: a pre-planted symlink would make wget -c or ">",
    # running as root, write outside the download dir. Require regular files.
    if [[ -L "$VERSION_FILE" ]]; then
      log "  警告: 版本标记是符号链接, 移除: $VERSION_FILE"
      rm -f "$VERSION_FILE" || die 1 "无法移除异常版本标记: $VERSION_FILE"
    fi
    if exists "$DL_FILE"; then
      if [[ -f "$DL_FILE" && ! -L "$DL_FILE" ]] &&
         [[ -f "$VERSION_FILE" ]] &&
         [[ "$(cat "$VERSION_FILE")" == "$remote_tag" ]]; then
        log "  服务端文件未变更, 从 $(stat -c %s "$DL_FILE") 字节处断点续传"
      else
        log "  服务端文件已变更(或本地文件/标记不可用), 删除本地文件重新下载"
        rm -f "$DL_FILE" || die 1 "无法删除旧下载文件: $DL_FILE"
      fi
    fi
    printf '%s\n' "$remote_tag" > "$VERSION_FILE" \
      || die 1 "无法写入版本标记: $VERSION_FILE"
  else
    log "  警告: 无法获取服务端版本信息, 删除本地文件重新下载(本次不续传)"
    rm -f "$DL_FILE" "$VERSION_FILE" || die 1 "无法清理旧下载文件: $DL_FILE"
  fi

  wget -c -t "$WGET_RETRY" -T "$WGET_TIMEOUT" -P "$DL_DIR" "$URL" \
    || die 1 "下载失败(已重试 ${WGET_RETRY} 次): $URL"

  [[ -s "$DL_FILE" ]] || die 1 "下载产物为空: $DL_FILE"
  DOWNLOAD_ACTIVE=0
  log "下载完成: $DL_FILE ($(du -h "$DL_FILE" | cut -f1))"
}

#--------------------------- Stage 2: extract ----------------------------------
stage2_extract() {
  log "Stage 2: 解压与包内容校验"
  SRC_FILES=()
  rm -rf "$EXTRACT_DIR"                # drop leftovers so old/new payloads cannot mix
  mkdir -p "$EXTRACT_DIR" || die 2 "无法创建解压目录: $EXTRACT_DIR"

  tar -xzf "$DL_FILE" -C "$EXTRACT_DIR" || die 2 "解压失败(包损坏或非 gzip/tar 格式): $DL_FILE"

  local i pattern
  local -a hits
  for i in "${!SRC_PATTERNS[@]}"; do
    pattern="${SRC_PATTERNS[$i]}"
    mapfile -t hits < <(find "$EXTRACT_DIR" -type f -wholename "$pattern" 2>/dev/null)
    (( ${#hits[@]} > 0 )) || die 2 "包内缺少文件(查找模式: $pattern), 终止安装"
    if (( ${#hits[@]} > 1 )); then
      # Warn on ambiguity: taking hits[0] may pick the wrong version.
      log "  警告: 模式 $pattern 匹配 ${#hits[@]} 个文件, 取第一个: ${hits[0]#"$EXTRACT_DIR"/}"
    fi
    [[ -s "${hits[0]}" ]] || die 2 "包内文件为空: ${hits[0]#"$EXTRACT_DIR"/}"
    SRC_FILES+=("${hits[0]}")
    log "  定位: ${DST_PATHS[$i]} <- ${hits[0]#"$EXTRACT_DIR"/}"
  done
  log "包内容校验通过 (${#SRC_FILES[@]}/${#SRC_PATTERNS[@]} 个文件)"
}

#--------------------------- Stage 3: backup -----------------------------------
stage3_backup() {
  log "Stage 3: 备份原文件 (*.ubak)"
  BACKED_UP=()
  local i dst
  for i in "${!DST_PATHS[@]}"; do
    dst="${DST_PATHS[$i]}"
    if [[ -d "$dst" ]]; then
      die 3 "目标路径是目录, 系统状态异常, 拒绝操作: $dst"
    fi
    # A dangling symlink fails -f, so it would be treated as "target absent"
    # and cp -f would write through the link, as root, outside the target dir.
    if [[ -L "$dst" && ! -e "$dst" ]]; then
      die 3 "目标是指向不存在文件的悬空符号链接, 拒绝操作: $dst"
    fi
    if [[ -f "$dst" ]]; then
      # If .ubak is a directory, cp succeeds by copying INTO it; rollback then
      # finds no regular .ubak, deletes the real target, and loses the backup.
      if [[ -d "$dst.ubak" ]]; then
        die 3 "备份路径是目录, 拒绝操作: $dst.ubak"
      fi
      cp -p "$dst" "$dst.ubak" || { rm -f "$dst.ubak"; die 3 "备份失败: $dst"; }
      BACKED_UP+=("$dst")
      log "  已备份: $dst -> $(basename "$dst").ubak"
    else
      # No original (fresh install): install as new, rollback just removes it.
      log "  跳过备份(目标不存在, 将作为新增安装): $dst"
    fi
  done
}

#--------------------------- Stage 4: install ----------------------------------
stage4_install() {
  log "Stage 4: 安装新文件(覆盖目标)"
  INSTALLED=()
  local i src dst size
  for i in "${!SRC_FILES[@]}"; do
    src="${SRC_FILES[$i]}"
    dst="${DST_PATHS[$i]}"
    if [[ -d "$dst" ]]; then
      die 4 "目标路径是目录, 拒绝替换: $dst"
    fi
    mkdir -p "$(dirname "$dst")" || die 4 "无法创建目标目录: $(dirname "$dst")"
    # Register BEFORE cp: cp can truncate/partially write the target before
    # failing, and rollback must still cover that file.
    INSTALLED+=("$dst")
    # cp -f onto an existing target keeps its inode, mode and owner; only the
    # content changes, and symlinks keep pointing at the same place.
    cp -f "$src" "$dst" || die 4 "复制失败: $src -> $dst"
    # -L dereferences symlinked targets: plain -c reports the link's own length
    # instead of the size actually installed.
    size=$(stat -Lc %s "$dst" 2>/dev/null) || size="?"
    log "  已安装: $dst (${size} 字节)"
  done
}

#--------------------------- Stage 5: commit -----------------------------------
stage5_commit() {
  log "Stage 5: 提交(删除备份)"
  local dst
  for dst in "${BACKED_UP[@]}"; do
    if rm -f "$dst.ubak"; then
      log "  已删除备份: $(basename "$dst").ubak"
    else
      err "  删除备份失败: $dst.ubak"
    fi
  done
  log "更新完成: ${#INSTALLED[@]} 个文件已就位, ${#BACKED_UP[@]} 个备份已删除"
}

#--------------------------- Single-instance lock ------------------------------
# Lock this script's own inode: no extra file, inode survives cleanup_download()
# removing /tmp/fullalarm, and a read-only fd avoids O_TRUNC on a planted link.
lock_abort() {  # never entered the pipeline: bypass on_exit, touch nothing
  err "$1"
  trap - EXIT INT TERM
  exit 5
}

acquire_lock() {
  local self="${BASH_SOURCE[0]}" rc
  [[ -r "$self" ]] || lock_abort "无法读取脚本自身作为运行锁: $self"
  exec 9<"$self" || lock_abort "无法打开脚本作为运行锁: $self"
  if LC_ALL=C flock -n -E 75 9; then
    return 0
  else
    rc=$?
  fi
  # -E 75 separates a real conflict (75) from flock/environment errors;
  # otherwise any failure is misreported as "another instance is running".
  if (( rc == 75 )); then
    lock_abort "已有实例正在运行, 本次跳过"
  fi
  lock_abort "flock 异常(rc=$rc), 拒绝在无互斥保护下继续"
}

#--------------------------- Main ----------------------------------------------
main() {
  # Reset state so sourcing / repeated calls in one shell cannot leak.
  SRC_FILES=(); BACKED_UP=(); INSTALLED=()
  ROLLED_BACK=0; ROLLBACK_FAILED=0; DOWNLOAD_ACTIVE=0
  stage0_precheck
  stage1_download
  stage2_extract
  stage3_backup
  stage4_install
  stage5_commit
}

# Run only when executed directly; tests source this file and drive stages.
# The lock stays out of the sourced path so tests never contend with each other.
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  acquire_lock
  main "$@"
fi
