#!/bin/bash
# Script pour extraire l'app.asar d'une AppImage ou exe
# Usage: bash scripts/extract-asar.sh <chemin-vers-appimage-ou-exe>

set -e

if [ -z "$1" ]; then
    echo "Usage: bash extract-asar.sh <chemin-vers-appimage.ou.exe>"
    exit 1
fi

INPUT="$1"
SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"

echo "=== Extraction de l'app.asar depuis $INPUT ==="

# Vérifier le type de fichier
FILETYPE=$(file "$INPUT")
echo "Type: $FILETYPE"

if echo "$FILETYPE" | grep -q "AppImage\|ELF.*executable"; then
    echo "→ AppImage détectée"
    7z x "$INPUT" -o/tmp/airfieldz-extract resources/app.asar -y > /dev/null 2>&1
    cp /tmp/airfieldz-extract/resources/app.asar "$SCRIPT_DIR/app.asar"
    echo "✓ app.asar extrait ($(ls -lh $SCRIPT_DIR/app.asar | awk '{print $5}'))"
    
elif echo "$FILETYPE" | grep -q "Nullsoft Installer\|PE32"; then
    echo "→ Installateur NSIS détecté"
    7z x "$INPUT" -o/tmp/airfieldz-extract -y > /dev/null 2>&1
    7z x "/tmp/airfieldz-extract/NSIS/\$PLUGINSDIR/app-64.7z" -o/tmp/airfieldz-extract-nsis -y > /dev/null 2>&1
    7z x "/tmp/airfieldz-extract-nsis/resources/app.asar" -o"$SCRIPT_DIR" -y > /dev/null 2>&1
    echo "✓ app.asar extrait ($(ls -lh $SCRIPT_DIR/app.asar | awk '{print $5}'))"
else
    echo "✗ Type de fichier non reconnu"
    exit 1
fi

echo ""
echo "Pour extraire le contenu: asar extract app.asar ./extracted/"
echo "Pour repackager: asar pack ./extracted/ app.asar"
rm -rf /tmp/airfieldz-extract /tmp/airfieldz-extract-nsis 2>/dev/null
