#!/bin/bash

set -e

APP_NAME="Passport-C-Media-Player"
APP_VERSION="0.1"
OUTPUT_NAME="${APP_NAME}-${APP_VERSION}-x86_64.AppImage"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

rm -rf AppDir/

echo -e "${GREEN}Building ${APP_NAME} AppImage...${NC}"

# Check if binary exists
if [ ! -f "passport-c-media-player" ]; then
    echo -e "${YELLOW}Binary not found. Building first...${NC}"
    make clean
    make
fi

# Create AppDir structure
echo -e "${GREEN}Setting up AppDir...${NC}"
mkdir -p AppDir/usr/bin
mkdir -p AppDir/usr/share/applications
mkdir -p AppDir/usr/share/icons/hicolor/256x256/apps

# Copy binary
cp passport-c-media-player AppDir/usr/bin/
chmod +x AppDir/usr/bin/passport-c-media-player

# Create desktop file directly in script (avoids copy conflicts)
cat > AppDir/passport-c-media-player.desktop << 'EOF'
[Desktop Entry]
Name=Passport-C Media Player
Comment=Turn your media library into an early 2000s cable box TV guide
Exec=passport-c-media-player
Icon=passport-c-media-player
Type=Application
Categories=AudioVideo;Player;TV;
Terminal=false
EOF

# Also copy to usr/share/applications for system integration
cp AppDir/passport-c-media-player.desktop AppDir/usr/share/applications/

# Copy and convert icon
echo -e "${GREEN}Setting up icon...${NC}"
if [ -f "logo.png" ]; then
    cp logo.png AppDir/usr/share/icons/hicolor/256x256/apps/passport-c-media-player.png
    cp logo.png AppDir/passport-c-media-player.png
else
    echo -e "${RED}Warning: logo.png not found!${NC}"
fi

# Create AppRun symlink
cd AppDir
ln -sf usr/bin/passport-c-media-player AppRun
cd ..

# Download linuxdeploy if not present
if [ ! -f "linuxdeploy-x86_64.AppImage" ]; then
    echo -e "${GREEN}Downloading linuxdeploy...${NC}"
    wget -q https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage
    chmod +x linuxdeploy-x86_64.AppImage
fi

# Build AppImage
echo -e "${GREEN}Creating AppImage...${NC}"
./linuxdeploy-x86_64.AppImage \
    --appdir AppDir \
    --output appimage \
    -d AppDir/usr/share/applications/passport-c-media-player.desktop \
    -i AppDir/usr/share/icons/hicolor/256x256/apps/passport-c-media-player.png

# Rename output file
# Use wildcard to find whatever AppImage was created (handles underscore/dash variations)
for file in Passport*.AppImage; do
    if [ -f "$file" ]; then
        mv "$file" "${OUTPUT_NAME}"
        break
    fi
done

if [ -f "${OUTPUT_NAME}" ]; then
    echo -e "${GREEN}Success! Created ${OUTPUT_NAME}${NC}"
    ls -lh "${OUTPUT_NAME}"
else
    echo -e "${RED}Error: AppImage creation failed!${NC}"
    exit 1
fi
