#!/bin/bash
set -e

APPSTORE_DIR="/Applications/AppStore.app"
BACKUP_DIR="/Applications/AppStore.app.orig"

RETRO_APP=""
if [ -d "/Applications/RetroStore.app" ]; then
    RETRO_APP="/Applications/RetroStore.app"
elif [ -d "/var/mobile/Applications" ]; then
    RETRO_APP=$(find /var/mobile/Applications -maxdepth 2 -type d -name "RetroStore.app" 2>/dev/null | head -n 1)
fi

echo "[RetroStore] Configuration de la redirection App Store..."

if [ -d "$APPSTORE_DIR" ]; then
    if [ ! -d "$BACKUP_DIR" ]; then
        echo "[RetroStore] Sauvegarde de l'App Store officiel..."
        cp -a "$APPSTORE_DIR" "$BACKUP_DIR"
    fi

    if [ -n "$RETRO_APP" ] && [ -d "$RETRO_APP" ]; then
        echo "[RetroStore] Remplacement des binaires par RetroStore..."
        mkdir -p /tmp/appstore_backup_icons
        cp -f "$APPSTORE_DIR"/Icon*.png /tmp/appstore_backup_icons/ 2>/dev/null || true
        cp -af "$RETRO_APP"/* "$APPSTORE_DIR"/
        cp -f /tmp/appstore_backup_icons/Icon*.png "$APPSTORE_DIR"/ 2>/dev/null || true
        rm -rf /tmp/appstore_backup_icons
        chmod -R 755 "$APPSTORE_DIR"
        chown -R root:wheel "$APPSTORE_DIR"
    else
        echo "[RetroStore] Configuration du lanceur d'ouverture..."
        cat << 'SUB_EOF' > "$APPSTORE_DIR/AppStore"
#!/bin/bash
if [ -x "/usr/bin/uiopen" ]; then
    /usr/bin/uiopen "retrostore://" || /usr/bin/uiopen "https://retrostore.tigrou.online/"
fi
SUB_EOF
        chmod 755 "$APPSTORE_DIR/AppStore"
    fi

    if [ -x "/usr/bin/uicache" ]; then
        /usr/bin/uicache
    fi
    killall -HUP SpringBoard 2>/dev/null || true
    echo "[RetroStore] Redirection activée avec succès !"
fi
