#!/bin/bash -e

# Install Proxmark3 from pre-built tarball or compile from source as fallback.
#
# Pre-built tarball: extracted from /tmp/pm3-prebuilt.tar.gz (staged by 00-run.sh)
# Compile fallback: triggered when /tmp/PM3_COMPILE_FROM_SOURCE exists

echo "=== Proxmark3 Installation ==="

# --- Check if we need to compile from source (fallback) ---
if [ -f /tmp/PM3_COMPILE_FROM_SOURCE ]; then
    echo "No pre-built tarball available — compiling from source"
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    if [ -f "${SCRIPT_DIR}/00-run-chroot-compile.sh" ]; then
        exec "${SCRIPT_DIR}/00-run-chroot-compile.sh"
    else
        echo "ERROR: Compile fallback script not found"
        exit 1
    fi
fi

# --- Pre-built tarball installation ---
if [ ! -f /tmp/pm3-prebuilt.tar.gz ]; then
    echo "ERROR: PM3 tarball not found at /tmp/pm3-prebuilt.tar.gz"
    echo "Set PM3_TARBALL env var or place a tarball in 02-pm3-install/files/"
    exit 1
fi

# Install runtime dependencies only (no build tools needed)
echo "Installing runtime dependencies..."
apt-get install -y \
    libreadline8t64 \
    libusb-1.0-0 \
    liblz4-1 \
    libbz2-1.0 \
    libjansson4 \
    libgd3t64 \
    libssl3t64 \
    libbluetooth3

# Detect the default user (first 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"
fi
DEFAULT_HOME=$(eval echo ~$DEFAULT_USER)
echo "Installing for user: $DEFAULT_USER (home: $DEFAULT_HOME)"

# Create installation directory
mkdir -p "$DEFAULT_HOME/.pm3/proxmark3"

# Extract pre-built tarball
# Tarball structure: pm3/{client/,firmware/,patches/,scripts/,pm3-flash-*,COMPONENT_VERSION}
echo "Extracting PM3 tarball..."
tar -xzf /tmp/pm3-prebuilt.tar.gz -C "$DEFAULT_HOME/.pm3/proxmark3" --strip-components=1

# Ensure _pm3.so symlink exists (critical for Python import)
if [ -f "$DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/libpm3rrg_rdv4.so" ] && \
   [ ! -f "$DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/_pm3.so" ]; then
    echo "Creating _pm3.so symlink..."
    cd "$DEFAULT_HOME/.pm3/proxmark3/client/pyscripts"
    ln -sf libpm3rrg_rdv4.so _pm3.so
fi

# Ensure flash utilities are executable
chmod +x "$DEFAULT_HOME/.pm3/proxmark3/pm3-flash-"* 2>/dev/null || true

# Install PM3 rebuild script (for on-device source rebuilds)
echo "Installing rebuild script..."
mkdir -p "$DEFAULT_HOME/.pm3/proxmark3/scripts"
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

# Apply HF booster detection patch
if [ -f "$PM3_HOME/patches/hf-booster-detection.patch" ]; then
    echo "Applying HF booster detection patch..."
    patch -p1 < "$PM3_HOME/patches/hf-booster-detection.patch"
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"

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

# Add Python path to environment
echo "Configuring Python path..."
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

# --- Verification ---
echo "Verifying installation..."

ERRORS=0

if [ -f "$DEFAULT_HOME/.pm3/proxmark3/client/proxmark3" ]; then
    echo "Client executable installed"
else
    echo "ERROR: Client executable not found"
    ERRORS=$((ERRORS + 1))
fi

# Verify library architecture
if [ -f "$DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/libpm3rrg_rdv4.so" ]; then
    LIB_ARCH=$(file "$DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/libpm3rrg_rdv4.so" | grep -o 'ARM aarch64\|x86-64\|ARM,')
    if [ "$LIB_ARCH" = "ARM aarch64" ]; then
        echo "Library architecture correct: $LIB_ARCH"
    else
        echo "ERROR: Library architecture mismatch! Expected ARM aarch64, got: $LIB_ARCH"
        ERRORS=$((ERRORS + 1))
    fi
fi

if [ -f "$DEFAULT_HOME/.pm3/proxmark3/client/pyscripts/pm3.py" ]; then
    echo "Python module installed"
else
    echo "ERROR: Python module not found"
    ERRORS=$((ERRORS + 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)"
    ERRORS=$((ERRORS + 1))
fi

if [ -f "$DEFAULT_HOME/.pm3/proxmark3/firmware/fullimage.elf" ]; then
    echo "Firmware files installed"
else
    echo "ERROR: Firmware files not found"
    ERRORS=$((ERRORS + 1))
fi

if [ -f "$DEFAULT_HOME/.pm3/proxmark3/pm3-flash-all" ]; then
    echo "Flash utilities installed"
else
    echo "WARNING: Flash utilities not found"
fi

if [ $ERRORS -gt 0 ]; then
    echo "ERROR: $ERRORS verification checks failed"
    exit 1
fi

# Clean up tarball
rm -f /tmp/pm3-prebuilt.tar.gz

# Print summary
echo "=== Proxmark3 installation complete ==="
echo "Installation: $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/"
if [ -f "$DEFAULT_HOME/.pm3/proxmark3/COMPONENT_VERSION" ]; then
    echo "Version info:"
    cat "$DEFAULT_HOME/.pm3/proxmark3/COMPONENT_VERSION"
fi
