#!/bin/bash -e

# Proxmark3 Client Build with Python Bindings
# Builds firmware + client + experimental Python library for Dangerous Pi
# Date: 2025-11-26

echo "=== Starting Proxmark3 build with Python bindings ==="

# Check if build can be skipped (manifest unchanged from previous build)
if [ -f /tmp/SKIP_PM3_BUILD ]; then
    echo "=== PM3 build manifest unchanged — checking cached installation ==="
    DEFAULT_USER=$(awk -F: '$3 >= 1000 && $3 < 65534 {print $1; exit}' /etc/passwd)
    DEFAULT_HOME=$(eval echo ~${DEFAULT_USER:-pi})
    if [ -f "$DEFAULT_HOME/.pm3/proxmark3/client/proxmark3" ] && \
       [ -f "$DEFAULT_HOME/.pm3/proxmark3/firmware/fullimage.elf" ]; then
        echo "✓ PM3 client binary present"
        echo "✓ PM3 firmware present"
        echo "=== Skipping Proxmark3 build (cached) ==="
        exit 0
    else
        echo "✗ PM3 binaries missing despite manifest match — rebuilding"
    fi
fi

# Install build dependencies
# apt-get update not needed: metadata inherited from stage0 (same build session)
echo "Installing build dependencies..."
apt-get install -y \
    cmake \
    python3-dev \
    swig \
    build-essential \
    libreadline-dev \
    libusb-1.0-0-dev \
    liblz4-dev \
    libbz2-dev \
    libjansson-dev \
    libc6-dev \
    pkg-config \
    git \
    gcc-arm-none-eabi \
    libnewlib-dev \
    ca-certificates \
    libssl-dev \
    libbluetooth-dev \
    libgd-dev

# Read pinned version config if available
PM3_REPO="https://github.com/RfidResearchGroup/proxmark3"
PM3_COMMIT=""
if [ -f /tmp/pm3-version.conf ]; then
    . /tmp/pm3-version.conf
fi

# Clone Proxmark3 repository
echo "Cloning Proxmark3 repository..."
cd /tmp
rm -rf proxmark3  # Clean any existing clone
git clone "$PM3_REPO" proxmark3
cd proxmark3
if [ -n "$PM3_COMMIT" ]; then
    echo "Checking out pinned commit: $PM3_COMMIT"
    git checkout "$PM3_COMMIT"
fi

# Apply LED PWM control patch (custom Dangerous Pi feature)
# Patch was copied to /tmp by 00-run.sh (pre-chroot script)
echo "Applying LED PWM control patch..."
if [ -f /tmp/led-pwm-control.patch ]; then
    patch -p1 < /tmp/led-pwm-control.patch
    if [ $? -eq 0 ]; then
        echo "✓ LED PWM control patch applied successfully"
    else
        echo "✗ WARNING: LED PWM control patch failed to apply cleanly"
    fi
    rm /tmp/led-pwm-control.patch
else
    echo "✗ WARNING: LED PWM control patch not found at /tmp/led-pwm-control.patch"
fi

# Add Dangerous Pi branding to version string
echo "Adding Dangerous Pi branding to version..."
sed -i 's/^fullgitinfo="Iceman"$/fullgitinfo="Iceman\/DangerousPi"/' tools/mkversion.sh
if grep -q 'fullgitinfo="Iceman/DangerousPi"' tools/mkversion.sh; then
    echo "✓ Version branding applied"
else
    echo "✗ WARNING: Version branding may not have applied correctly"
fi

# Build firmware (existing functionality)
echo "Building firmware..."
cat > Makefile.platform << EOF
PLATFORM=PM3GENERIC
LED_ORDER=PM3EASY
EOF
make clean && make -j$(nproc)

# Apply fixes to CMakeLists.txt for Python bindings
# These fix undefined symbol errors in the SWIG library

# Fix 1: Add qrcode.c (fixes "undefined symbol: qrcode_print_matrix_utf8")
echo "Applying qrcode fix to experimental library..."
sed -i '/TARGET_SOURCES.*pm3rrg_rdv4_experimental/,/)/s|\(${PM3_ROOT}/client/src/wiegand_formatutils.c\)|\1\n    ${PM3_ROOT}/client/src/qrcode/qrcode.c|' \
    client/experimental_lib/CMakeLists.txt

# Fix 2: Add pla.c (fixes "undefined symbol: pla_parse_ecp_subcommand")
echo "Applying pla.c fix to experimental library..."
sed -i 's|\(${PM3_ROOT}/client/src/pm3\.c\)|${PM3_ROOT}/client/src/pla.c\n        \1|' \
    client/experimental_lib/CMakeLists.txt

# Verify the fixes were applied
if grep -q "qrcode/qrcode.c" client/experimental_lib/CMakeLists.txt; then
    echo "✓ qrcode fix applied successfully"
else
    echo "✗ WARNING: qrcode fix may not have applied correctly"
fi

if grep -q "pla\.c" client/experimental_lib/CMakeLists.txt; then
    echo "✓ pla.c fix applied successfully"
else
    echo "✗ WARNING: pla.c fix may not have applied correctly"
fi

# Build client with Python bindings
echo "Building PM3 client..."
cd client
mkdir -p build
cd build
cmake .. -DBUILD_PYTHON_LIB=ON
make -j$(nproc)

# Build experimental Python library
echo "Building experimental Python library..."
cd ../experimental_lib
./00make_swig.sh
./01make_lib.sh

# Detect the default user (cloud-init compatible)
# Find first user with UID >= 1000 (excluding nobody)
DEFAULT_USER=$(awk -F: '$3 >= 1000 && $3 < 65534 {print $1; exit}' /etc/passwd)
if [ -z "$DEFAULT_USER" ]; then
    DEFAULT_USER="pi"  # Fallback to pi if detection fails
fi
DEFAULT_HOME=$(eval echo ~$DEFAULT_USER)

echo "Detected default user: $DEFAULT_USER (home: $DEFAULT_HOME)"

# Create installation directories
echo "Creating installation directories..."
mkdir -p $DEFAULT_HOME
mkdir -p $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts
mkdir -p $DEFAULT_HOME/.pm3/proxmark3/firmware
mkdir -p $DEFAULT_HOME/.pm3/proxmark3/patches
mkdir -p $DEFAULT_HOME/.pm3/proxmark3/scripts

# Install client executable
echo "Installing PM3 client..."
cp /tmp/proxmark3/client/build/proxmark3 $DEFAULT_HOME/.pm3/proxmark3/client/

# Install flash utilities
echo "Installing flash utilities..."
cp /tmp/proxmark3/pm3-flash-all $DEFAULT_HOME/.pm3/proxmark3/
cp /tmp/proxmark3/pm3-flash-bootrom $DEFAULT_HOME/.pm3/proxmark3/
cp /tmp/proxmark3/pm3-flash-fullimage $DEFAULT_HOME/.pm3/proxmark3/
chmod +x $DEFAULT_HOME/.pm3/proxmark3/pm3-flash-*

# Install LED PWM control patch for future rebuilds
echo "Installing LED PWM control patch..."
if [ -f /tmp/led-pwm-control.patch ]; then
    cp /tmp/led-pwm-control.patch $DEFAULT_HOME/.pm3/proxmark3/patches/
    echo "✓ LED PWM control patch saved for future rebuilds"
fi

# Install PM3 rebuild script
echo "Creating PM3 rebuild script..."
cat > $DEFAULT_HOME/.pm3/proxmark3/scripts/rebuild-pm3.sh << 'REBUILD_EOF'
#!/bin/bash
# Rebuild Proxmark3 client and firmware with LED PWM control patch
# Usage: ./rebuild-pm3.sh [--flash]

set -e

PM3_HOME="$HOME/.pm3/proxmark3"
BUILD_DIR="/tmp/proxmark3-rebuild"
PATCH_FILE="$PM3_HOME/patches/led-pwm-control.patch"

echo "=== Proxmark3 Rebuild Script ==="
echo "This will rebuild the PM3 client and firmware with LED PWM control."
echo ""

# Check for ARM toolchain
if ! command -v arm-none-eabi-gcc &> /dev/null; then
    echo "ERROR: ARM toolchain not found. Install with:"
    echo "  sudo apt install gcc-arm-none-eabi"
    exit 1
fi

# Clean previous build
rm -rf "$BUILD_DIR"

# Clone fresh copy
echo "Cloning Proxmark3 repository..."
git clone --depth 1 https://github.com/RfidResearchGroup/proxmark3 "$BUILD_DIR"
cd "$BUILD_DIR"

# Apply LED PWM control patch
if [ -f "$PATCH_FILE" ]; then
    echo "Applying LED PWM control patch..."
    patch -p1 < "$PATCH_FILE"
    echo "✓ Patch applied"
else
    echo "WARNING: LED patch not found at $PATCH_FILE"
fi

# Add Dangerous Pi branding to version string
echo "Adding Dangerous Pi branding..."
sed -i 's/^fullgitinfo="Iceman"$/fullgitinfo="Iceman\/DangerousPi"/' tools/mkversion.sh

# Configure build
echo "Configuring build..."
cat > Makefile.platform << EOF
PLATFORM=PM3GENERIC
LED_ORDER=PM3EASY
EOF

# Build firmware and client
echo "Building firmware (this takes a while on Pi Zero)..."
make clean
make -j$(nproc)

# Build client with Python bindings
echo "Building client..."
cd client
mkdir -p build
cd build
cmake .. -DBUILD_PYTHON_LIB=ON
make -j$(nproc)

# Build experimental Python library
echo "Building Python bindings..."
cd ../experimental_lib
./00make_swig.sh
./01make_lib.sh
cd "$BUILD_DIR"

# Backup current installation
echo "Backing up current installation..."
if [ -f "$PM3_HOME/client/proxmark3" ]; then
    cp "$PM3_HOME/client/proxmark3" "$PM3_HOME/client/proxmark3.bak"
fi
if [ -f "$PM3_HOME/firmware/fullimage.elf" ]; then
    cp "$PM3_HOME/firmware/fullimage.elf" "$PM3_HOME/firmware/fullimage.elf.bak"
fi

# Install new binaries
echo "Installing new client..."
cp "$BUILD_DIR/client/build/proxmark3" "$PM3_HOME/client/"
cp "$BUILD_DIR/client/experimental_lib/build/libpm3rrg_rdv4.so" "$PM3_HOME/client/pyscripts/"
cp "$BUILD_DIR/client/pyscripts/*.py" "$PM3_HOME/client/pyscripts/"

echo "Installing new firmware..."
cp "$BUILD_DIR/bootrom/obj/bootrom.elf" "$PM3_HOME/firmware/"
cp "$BUILD_DIR/armsrc/obj/fullimage.elf" "$PM3_HOME/firmware/"

# Update flash utilities
echo "Updating flash utilities..."
cp "$BUILD_DIR/pm3-flash-all" "$PM3_HOME/"
cp "$BUILD_DIR/pm3-flash-bootrom" "$PM3_HOME/"
cp "$BUILD_DIR/pm3-flash-fullimage" "$PM3_HOME/"
chmod +x "$PM3_HOME/pm3-flash-"*

# Update version
echo "Updating version info..."
cd "$BUILD_DIR"
git describe --always --tags > "$PM3_HOME/VERSION.txt"
echo "Build date: $(date -u +"%Y-%m-%d %H:%M:%S UTC")" >> "$PM3_HOME/VERSION.txt"
echo "Built with LED PWM control patch" >> "$PM3_HOME/VERSION.txt"

echo ""
echo "=== Build Complete ==="
echo "New client: $PM3_HOME/client/proxmark3"
echo "New firmware: $PM3_HOME/firmware/"
echo ""

# Flash if requested
if [ "$1" == "--flash" ]; then
    echo "Flashing firmware to connected device..."
    cd "$PM3_HOME"
    ./pm3-flash-all
    echo "✓ Flash complete"
else
    echo "To flash the new firmware, run:"
    echo "  cd $PM3_HOME && ./pm3-flash-all"
fi

# Cleanup
rm -rf "$BUILD_DIR"
echo "✓ Cleanup complete"
REBUILD_EOF
chmod +x $DEFAULT_HOME/.pm3/proxmark3/scripts/rebuild-pm3.sh

# Install Python bindings
echo "Installing Python bindings..."
cp /tmp/proxmark3/client/experimental_lib/build/libpm3rrg_rdv4.so $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/
cp /tmp/proxmark3/client/pyscripts/*.py $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/

# Create _pm3.so symlink for Python import (CRITICAL - this is what pm3.py imports)
echo "Creating Python module symlink..."
cd $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts
ln -sf libpm3rrg_rdv4.so _pm3.so

# Install firmware files
echo "Installing firmware files..."
cp /tmp/proxmark3/bootrom/obj/bootrom.elf $DEFAULT_HOME/.pm3/proxmark3/firmware/
cp /tmp/proxmark3/armsrc/obj/fullimage.elf $DEFAULT_HOME/.pm3/proxmark3/firmware/

# Create version file for tracking
echo "Creating version file..."
cd /tmp/proxmark3
git describe --always --tags > $DEFAULT_HOME/.pm3/proxmark3/VERSION.txt
echo "Build date: $(date -u +"%Y-%m-%d %H:%M:%S UTC")" >> $DEFAULT_HOME/.pm3/proxmark3/VERSION.txt

# Set proper ownership
echo "Setting ownership..."
chown -R $DEFAULT_USER:$DEFAULT_USER $DEFAULT_HOME/.pm3

# Add Python path to environment (for systemd services)
echo "Configuring Python path..."
# Ensure .bashrc exists
touch $DEFAULT_HOME/.bashrc
if ! grep -q "PYTHONPATH.*\.pm3" $DEFAULT_HOME/.bashrc; then
    echo 'export PYTHONPATH=$HOME/.pm3/proxmark3/client/pyscripts:$PYTHONPATH' >> $DEFAULT_HOME/.bashrc
fi

# Verify installation
echo "Verifying installation..."
if [ -f $DEFAULT_HOME/.pm3/proxmark3/client/proxmark3 ]; then
    echo "✓ Client executable installed"
else
    echo "✗ ERROR: Client executable not found"
    exit 1
fi

# Verify library architecture matches the target platform
echo "Verifying library architecture..."
LIB_ARCH=$(file $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/libpm3rrg_rdv4.so | grep -o 'ARM aarch64\|x86-64\|ARM,')
EXPECTED_ARCH="ARM aarch64"
if [ "$LIB_ARCH" = "$EXPECTED_ARCH" ]; then
    echo "✓ Library architecture correct: $LIB_ARCH"
else
    echo "✗ ERROR: Library architecture mismatch!"
    echo "  Expected: $EXPECTED_ARCH"
    echo "  Got: $LIB_ARCH"
    echo "  The library was built for the wrong architecture."
    exit 1
fi

if [ -f $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/pm3.py ]; then
    echo "✓ Python module installed"
else
    echo "✗ ERROR: Python module not found"
    exit 1
fi

if [ -f $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/_pm3.so ]; then
    echo "✓ Python bindings library installed (_pm3.so)"
else
    echo "✗ ERROR: Python bindings library not found (_pm3.so)"
    echo "  Expected symlink: _pm3.so -> libpm3rrg_rdv4.so"
    exit 1
fi

if [ -f $DEFAULT_HOME/.pm3/proxmark3/firmware/fullimage.elf ]; then
    echo "✓ Firmware files installed"
else
    echo "✗ ERROR: Firmware files not found"
    exit 1
fi

if [ -f $DEFAULT_HOME/.pm3/proxmark3/pm3-flash-all ]; then
    echo "✓ Flash utilities installed"
else
    echo "✗ WARNING: Flash utilities not found (flashing from UI will not work)"
fi

if [ -f $DEFAULT_HOME/.pm3/proxmark3/patches/led-pwm-control.patch ]; then
    echo "✓ LED PWM control patch saved"
else
    echo "✗ WARNING: LED PWM control patch not saved"
fi

if [ -f $DEFAULT_HOME/.pm3/proxmark3/scripts/rebuild-pm3.sh ]; then
    echo "✓ Rebuild script installed"
else
    echo "✗ WARNING: Rebuild script not installed"
fi

# Save build manifest for future cache checks
if [ -f /tmp/pm3-build-manifest ]; then
    mkdir -p /opt/dangerous-pi
    cp /tmp/pm3-build-manifest /opt/dangerous-pi/.pm3-build-manifest
    echo "✓ Build manifest saved for cache"
fi

# Print summary
echo "=== Proxmark3 build complete ==="
echo "Installation location: $DEFAULT_HOME/.pm3/proxmark3/"
echo "Client: $DEFAULT_HOME/.pm3/proxmark3/client/proxmark3"
echo "Flash utils: $DEFAULT_HOME/.pm3/proxmark3/pm3-flash-all"
echo "Python: $DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/pm3.py"
echo "Firmware: $DEFAULT_HOME/.pm3/proxmark3/firmware/"
cat $DEFAULT_HOME/.pm3/proxmark3/VERSION.txt

echo "✓ Proxmark3 installation successful"
