#!/usr/bin/env bash
if [ "$#" -ne 2 ]; then
  printf '用法: bash report.sh 日志文件 输出目录\n' >&2
  exit 2
fi
input=$1
out=$2
if [ ! -f "$input" ] || [ ! -r "$input" ]; then
  printf '无法读取: %s\n' "$input" >&2
  exit 1
fi
if [ ! -d "$out" ]; then
  printf '输出目录不存在: %s\n' "$out" >&2
  exit 1
fi
target="$out/summary.txt"
if [ "$input" -ef "$target" ]; then
  printf '输入日志与摘要是同一文件。\n' >&2
  exit 1
fi
matches=$(grep -F ' ERROR ' "$input")
code=$?
if [ "$code" -gt 1 ]; then
  printf '检索出错，未写入摘要。\n' >&2
  exit 1
fi
if [ -z "$matches" ]; then
  printf '' > "$target" || exit 1
else
  set -o pipefail
  printf '%s\n' "$matches" | cut -d ' ' -f 4 | sort | uniq -c | sort -nr > "$target"
  if [ "$?" -ne 0 ]; then
    printf '写入失败，请检查摘要是否完整。\n' >&2
    exit 1
  fi
fi
printf '写入 %s\n' "$target"
