#!/bin/bash

SOURCE_DIR="${1:-./}"  # First argument or current directory as default
OUTPUT_FILE="${2:-iupcocoa_nibs.m}"  # Second argument or default filename
TEMP_DIR="${TMPDIR:-/tmp}/xib_processing_$$"

if ! command -v ibtool &> /dev/null; then
    echo "Error: ibtool is not installed or not in PATH" >&2
    echo "Install Xcode Command Line Tools" >&2
    exit 1
fi

mkdir -p "$TEMP_DIR"

process_xib() {
    local xib_path="$1"
    local xib_name="$(basename "$xib_path" .xib)"
    local nib_path="$TEMP_DIR/${xib_name}.nib"

    /usr/bin/ibtool --output-format human-readable-text --compile "$nib_path" "$xib_path"

    if [ $? -ne 0 ]; then
        echo "Error: Failed to compile $xib_name.xib" >&2
        return 1
    fi

    local hex_dump=$(hexdump -v -e '1 1 "0x%02x,"' "$nib_path")
    local hex_length=$(stat -f "%z" "$nib_path")

    cat <<EOF

@implementation NSNib (${xib_name})

+(instancetype)${xib_name}
{
  NSData * data = [NSData dataWithBytesNoCopy:(void*)(const unsigned char[])
  {
${hex_dump}
  } length:(NSUInteger){ ${hex_length} } freeWhenDone:NO];
  NSNib * result = [[NSNib alloc] initWithNibData:data bundle:nil];
  return result;
}

@end
EOF
}

echo -e "// Code generated by xib.sh; DO NOT EDIT.\n" > "$OUTPUT_FILE"
echo "#import <Cocoa/Cocoa.h>" >> "$OUTPUT_FILE"

xib_count=0
for xib_file in "$SOURCE_DIR"/*.xib; do
    if [ -f "$xib_file" ]; then
        process_xib "$xib_file" >> "$OUTPUT_FILE"
        if [ $? -eq 0 ]; then
            ((xib_count++))
        fi
    fi
done

rm -rf "$TEMP_DIR"

if [ $xib_count -eq 0 ]; then
    echo "Warning: No XIB files found in $SOURCE_DIR" >&2
    exit 1
else
    echo "Successfully processed $xib_count XIB file(s)"
    echo "Output written to: $OUTPUT_FILE"
fi
