#!/bin/bash
# Java Class Decompiler using CFR
# Usage: ./decompile.sh <input_dir> <output_dir> [cfr_jar]

set -e

INPUT_DIR="${1:?Usage: decompile.sh <input_dir> <output_dir> [cfr_jar]}"
OUTPUT_DIR="${2:?Usage: decompile.sh <input_dir> <output_dir> [cfr_jar]}"
CFR_JAR="${3:-$(dirname "$0")/cfr.jar}"

# Check CFR exists
if [ ! -f "$CFR_JAR" ]; then
    echo "Error: CFR jar not found at $CFR_JAR"
    echo "Download from: https://github.com/leibnitz27/cfr/releases"
    exit 1
fi

# Check Java installed
if ! command -v java &> /dev/null; then
    echo "Error: Java not found. Please install Java 8+"
    exit 1
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Find all .class files
CLASS_FILES=$(find "$INPUT_DIR" -name "*.class" -type f)
TOTAL=$(echo "$CLASS_FILES" | wc -l)
CURRENT=0
SUCCESS=0
FAILED=0

echo "Found $TOTAL class files to decompile"
echo "Output directory: $OUTPUT_DIR"
echo "---"

# Decompile each file
while IFS= read -r class_file; do
    [ -z "$class_file" ] && continue
    CURRENT=$((CURRENT + 1))

    # Get relative path
    rel_path="${class_file#$INPUT_DIR/}"
    # Convert .class to .java
    java_path="${rel_path%.class}.java"
    java_output="$OUTPUT_DIR/$java_path"
    java_dir=$(dirname "$java_output")

    # Create directory
    mkdir -p "$java_dir"

    # Decompile
    if java -jar "$CFR_JAR" "$class_file" --outputdir "$OUTPUT_DIR" --silent true 2>/dev/null; then
        SUCCESS=$((SUCCESS + 1))
    else
        FAILED=$((FAILED + 1))
        echo "[$CURRENT/$TOTAL] FAILED: $rel_path"
    fi

    # Progress indicator
    if [ $((CURRENT % 100)) -eq 0 ]; then
        echo "Progress: $CURRENT/$TOTAL decompiled"
    fi
done <<< "$CLASS_FILES"

echo "---"
echo "Decompilation complete!"
echo "Total: $TOTAL | Success: $SUCCESS | Failed: $FAILED"
echo "Output: $OUTPUT_DIR"
