#!/bin/sh
ZIPFILE="$1"
TARGET_FILE="$2"
OUTPUT_DIR="$3"
TMPDIR_FOR_VERIFY="$OUTPUT_DIR/.vunzip"
mkdir -p "$TMPDIR_FOR_VERIFY"

abort_verify() {
  echo "! $1"
  exit 1
}
extract_and_verify() {
  local file="$1"
  local file_name=$(basename "$file")
  local file_path="$OUTPUT_DIR/$file_name"
  local hash_path="$TMPDIR_FOR_VERIFY/${file_name}.sha256"

  unzip -o "$ZIPFILE" "$file" -d "$OUTPUT_DIR" >&2
  [ -f "$file_path" ] || abort_verify "$file 不存在"

  unzip -o "$ZIPFILE" "$file.sha256" -d "$TMPDIR_FOR_VERIFY" >&2
  [ -f "$hash_path" ] || abort_verify "$file.sha256 不存在"

  echo "$(cat "$hash_path")  $file_path" | sha256sum -c -s - >&2
  [ $? -eq 0 ] || abort_verify "$file 完整性校验失败"
}

extract_and_verify "$TARGET_FILE"
echo "$TARGET_FILE 校验通过"
exit 0
