#!/usr/bin/env bash
set -Eeuo pipefail

if [[ $# -lt 1 ]]; then
  echo "用法: $0 /path/to/pdf_folder [並行數]"
  exit 1
fi

TARGET_DIR="$1"
JOBS="${2:-2}"
TMP_DIR="${TARGET_DIR%/}/tmp"
PROGRESS_DIR="${TMP_DIR}/.progress"

if [[ ! -d "$TARGET_DIR" ]]; then
  echo "錯誤：資料夾不存在：$TARGET_DIR"
  exit 1
fi

if ! command -v gs >/dev/null 2>&1; then
  echo "錯誤：找不到 gs，請先安裝 Ghostscript"
  exit 1
fi

if ! [[ "$JOBS" =~ ^[1-9][0-9]*$ ]]; then
  echo "錯誤：並行數必須是正整數"
  exit 1
fi

mkdir -p "$TMP_DIR" "$PROGRESS_DIR"

shopt -s nullglob
pdf_files=("$TARGET_DIR"/*.pdf "$TARGET_DIR"/*.PDF)
files=()
for pdf in "${pdf_files[@]}"; do
  [[ -f "$pdf" ]] && files+=("$pdf")
done

total="${#files[@]}"
if [[ $total -eq 0 ]]; then
  echo "在 $TARGET_DIR 找不到 PDF 檔案"
  exit 0
fi

success=0
failed=0
started=0
running=0
completed=0

action_compress() {
  local pdf="$1"
  local base_name tmp_file marker_ok marker_fail

  base_name="$(basename "$pdf")"
  tmp_file="$TMP_DIR/$base_name"
  marker_ok="$PROGRESS_DIR/${base_name}.ok"
  marker_fail="$PROGRESS_DIR/${base_name}.fail"

  if gs \
    -sDEVICE=pdfwrite \
    -dCompatibilityLevel=1.4 \
    -dPDFSETTINGS=/ebook \
    -dNOPAUSE \
    -dQUIET \
    -dBATCH \
    -dShowAnnots=false \
    -sOutputFile="$tmp_file" \
    "$pdf" >/dev/null 2>&1; then
    if [[ -s "$tmp_file" ]]; then
      mv -f "$tmp_file" "$pdf"
      : > "$marker_ok"
    else
      rm -f "$tmp_file"
      : > "$marker_fail"
    fi
  else
    rm -f "$tmp_file"
    : > "$marker_fail"
  fi
}

show_progress() {
  success=$(find "$PROGRESS_DIR" -maxdepth 1 -type f -name '*.ok' | wc -l)
  failed=$(find "$PROGRESS_DIR" -maxdepth 1 -type f -name '*.fail' | wc -l)
  completed=$((success + failed))
  running=$((started - completed))
  (( running < 0 )) && running=0
  percent=$(( completed * 100 / total ))
  echo "進度：${percent}% | 已完成 $completed/$total | 成功 $success | 失敗 $failed | 執行中 $running"
}

pids=()

for pdf in "${files[@]}"; do
  while [[ $(jobs -pr | wc -l) -ge $JOBS ]]; do
    wait -n
    show_progress
  done

  ((started+=1))
  echo "[$started/$total] 已排入：$(basename "$pdf")"
  action_compress "$pdf" &
done

while [[ $(jobs -pr | wc -l) -gt 0 ]]; do
  wait -n
  show_progress
done

show_progress
echo "全部完成：成功 $success，失敗 $failed，總數 $total"

rm -f "$PROGRESS_DIR"/*.ok "$PROGRESS_DIR"/*.fail 2>/dev/null || true
rmdir "$PROGRESS_DIR" 2>/dev/null || true
rmdir "$TMP_DIR" 2>/dev/null || true

