#!/bin/sh
# Compare keys (lines starting with #) in .txt from new/ with original: count, list, ogg renames.
# Output: YAML. renamed_files only for keys present in both files.
# Usage: compare-keys.sh [-n] [new_dir] [content.uqm]
#   -n  only not ok and no_original (omit ok)
# Key lines are normalized (trailing spaces stripped) before comparison.

trim_tail() { sed -E 's/\s+$//'; }

NOT_OK_ONLY=0
case "${1:-}" in -n|--not-ok-only) NOT_OK_ONLY=1; shift ;; esac
NEW_DIR="${1:-unpack/tmp-repack/new}"
CONTENT_ZIP="${2:-/usr/share/games/uqm/content/packages/uqm-0.8.0-content.uqm}"

# From key line "#(KEY)\tfile.ogg" or "#(KEY)" output key and value (part after tab)
extract_kv() {
  awk -F'\t' '{
    key = $1
    gsub(/^#\(|\)$/, "", key)
    val = ($2 != "" ? $2 : "")
    if (key != "") print key "\t" val
  }'
}

# From two key files output orig_ogg to new_ogg pairs (only where key in both and values differ)
renamed_pairs() {
  awk -F'\t' '
    NR==FNR { okey[$1]=$2; next }
    { nkey[$1]=$2 }
    END {
      for (k in okey)
        if (k in nkey && okey[k] != "" && nkey[k] != "" && okey[k] != nkey[k])
          print okey[k] "\t" nkey[k]
    }
  ' "$1" "$2"
}

first=1
for f in $(find "$NEW_DIR" -name '*.txt' | sort); do
  rel="${f#$NEW_DIR/}"
  keys_ours=$(grep '^#' "$f" 2>/dev/null | trim_tail | wc -l | tr -d ' \t\r\n') || keys_ours=0
  keys_orig=$(unzip -p "$CONTENT_ZIP" "$rel" 2>/dev/null | grep '^#' | trim_tail | wc -l | tr -d ' \t\r\n') || true

  if [ -z "$keys_orig" ] || ! unzip -l -q "$CONTENT_ZIP" "$rel" >/dev/null 2>&1; then
    [ "$first" = 1 ] && first=0 || echo ""
    echo "- name: $rel"
    echo "  status: no_original"
    continue
  fi

  t_orig=$(mktemp)
  t_ours=$(mktemp)
  t_orig_kv=$(mktemp)
  t_ours_kv=$(mktemp)
  unzip -p "$CONTENT_ZIP" "$rel" 2>/dev/null | grep '^#' | trim_tail > "$t_orig"
  grep '^#' "$f" 2>/dev/null | trim_tail > "$t_ours"
  unzip -p "$CONTENT_ZIP" "$rel" 2>/dev/null | grep '^#' | trim_tail | extract_kv > "$t_orig_kv"
  grep '^#' "$f" 2>/dev/null | trim_tail | extract_kv > "$t_ours_kv"

  same_keys=0
  [ "$keys_orig" = "$keys_ours" ] && diff -q "$t_orig" "$t_ours" >/dev/null 2>&1 && same_keys=1

  if [ "$same_keys" = 1 ]; then
    [ "$NOT_OK_ONLY" = 1 ] && continue
  fi
  [ "$first" = 1 ] && first=0 || echo ""
  echo "- name: $rel"
  if [ "$same_keys" = 1 ]; then
    echo "  status: ok"
  else
    echo "  status: not ok"
    echo "  keys_count:"
    echo "    orig: $keys_orig"
    echo "    new: $keys_ours"
    rename_list=$(renamed_pairs "$t_orig_kv" "$t_ours_kv")
    if [ -n "$rename_list" ]; then
      echo "  renamed_files:"
      echo "$rename_list" | while IFS='	' read -r from to; do
        echo "    - name: $from"
        echo "      to: $to"
      done
    fi
    cp "$f" "$f.ru"
    unzip -p "$CONTENT_ZIP" "$rel" > "$f.en"
  fi

  rm -f "$t_orig" "$t_ours" "$t_orig_kv" "$t_ours_kv"
done
