#!/bin/bash

# Script to create a SUPER LEAN portable bundle for GTK2 Media Player
# This version only bundles essential GTK2 libs and libmpv.
# It depends on the host system for video codecs (FFmpeg).

# Ensure we are in the project root
cd "$(dirname "$0")/.."

APP_NAME="gtk2-mpv-player"
BUNDLE_DIR="${APP_NAME}-lean"

echo "Creating SUPER LEAN portable bundle in ${BUNDLE_DIR}..."

# 1. Clean and Build
make clean
make

if [ ! -f "$APP_NAME" ]; then
    echo "Build failed. Exiting."
    exit 1
fi

# 2. Create directory structure
rm -rf "$BUNDLE_DIR"
mkdir -p "$BUNDLE_DIR/bin"
mkdir -p "$BUNDLE_DIR/lib"

# 3. Copy executable
cp "$APP_NAME" "$BUNDLE_DIR/bin/"

# 4. Gather dependencies
echo "Gathering minimal dependencies..."

# In LEAN mode, we EXCLUDE all FFmpeg/Codec libraries.
# This assumes the host has them or that basic playback is enough.
EXCLUDES="libavcodec|libavfilter|libavformat|libavutil|libswresample|libswscale|libpostproc|libx264|libx265|libvpx|libopus|libvorbis|libtheora|libaom|libdav1d|librav1e|libSvtAv1Enc|libplacebo|libcrypto|libssl|libgnutls|libxml2|libfontconfig|libfreetype|libdbus|libasound|libpulse|libudev|libsystemd|libc\.so|libm\.so|libdl\.so|librt\.so|libpthread\.so|libX11|libxcb"

# Use temporary file to track libs
TEMP_LIBS=$(mktemp)

# Get direct dependencies only
ldd "$APP_NAME" | grep "=> /" | awk '{print $3}' >> "$TEMP_LIBS"

# Add libmpv (required)
if [ -f "lib/libmpv.so.2" ]; then
    cp -v "lib/libmpv.so.2" "$BUNDLE_DIR/lib/"
fi

# Copy filtered libs
sort -u "$TEMP_LIBS" | while read -r LIB; do
    LIB_BASE=$(basename "$LIB")
    if ! echo "$LIB_BASE" | grep -qE "$EXCLUDES"; then
        if [ -f "$LIB" ]; then
            cp -nv "$LIB" "$BUNDLE_DIR/lib/" 2>/dev/null
        fi
    fi
done

rm "$TEMP_LIBS"

# 5. Strip symbols to save space
echo "Stripping symbols..."
strip --strip-unneeded "$BUNDLE_DIR/bin/$APP_NAME"
find "$BUNDLE_DIR/lib" -name "*.so*" -exec strip --strip-unneeded {} \; 2>/dev/null

# 6. Create launch script
cat > "$BUNDLE_DIR/launch.sh" <<EOF
#!/bin/bash
DIR="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd)"
export LD_LIBRARY_PATH="\$DIR/lib:\$LD_LIBRARY_PATH"
exec "\$DIR/bin/$APP_NAME" "\$@"
EOF

chmod +x "$BUNDLE_DIR/launch.sh"

echo "------------------------------------------------"
echo "LEAN bundle created in ${BUNDLE_DIR}"
echo "To run, use: cd ${BUNDLE_DIR} && ./launch.sh"
echo "Note: This version requires system codecs to be present."
echo "------------------------------------------------"
