#!/usr/bin/env bash
# Wsamiaw HWID — same algorithm as the client (requires Java 11+ or JDK).
set -euo pipefail

if ! command -v java >/dev/null 2>&1; then
  echo "Java not found. Install Java (same as Minecraft) or use Wsalauncher to see your HWID." >&2
  exit 1
fi

dir="$(mktemp -d 2>/dev/null || mktemp -d -t wsamiaw-hwid)"
cleanup() { rm -rf "$dir"; }
trap cleanup EXIT

cat > "$dir/HwidCli.java" <<'EOF'
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

class HwidCli {
    public static void main(String[] args) {
        System.out.println(compute());
    }

    static String compute() {
        StringBuilder sb = new StringBuilder();
        sb.append(System.getProperty("os.name", ""));
        sb.append('|').append(System.getProperty("os.arch", ""));
        sb.append('|').append(System.getProperty("user.name", ""));
        String proc = System.getenv("PROCESSOR_IDENTIFIER");
        if (proc != null) sb.append('|').append(proc);
        return sha256Hex(sb.toString()).substring(0, 32);
    }

    static String sha256Hex(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder out = new StringBuilder();
            for (byte b : digest) out.append(String.format("%02x", b));
            return out.toString();
        } catch (Exception e) {
            return Integer.toHexString(input.hashCode());
        }
    }
}
EOF

if java "$dir/HwidCli.java" 2>/dev/null; then
  exit 0
fi

if command -v javac >/dev/null 2>&1; then
  javac -d "$dir" "$dir/HwidCli.java"
  exec java -cp "$dir" HwidCli
fi

echo "Need Java 11+ (java HwidCli.java) or a JDK (javac)." >&2
exit 1
