#!/bin/bash

APP_NAME="budget"
INSTALL_DIR="/opt/$APP_NAME"
DESKTOP_ENTRY="/usr/share/applications/$APP_NAME.desktop"
ICON_PATH="$INSTALL_DIR/resources/icons/budget.png"

# Detect system architecture
ARCH=$(uname -m)
case "$ARCH" in
    x86_64)   BIN_FILE="budget-linux_x64" ;;
    arm64)    BIN_FILE="budget-linux_arm64" ;;
    armhf)    BIN_FILE="budget-linux_armhf" ;;
    *)        echo "Unsupported architecture: $ARCH"; exit 1 ;;
esac

# Check if the binary exists in the bin directory
if [ ! -f "bin/$BIN_FILE" ]; then
    echo "Error: Binary file 'bin/$BIN_FILE' not found"
    exit 1
fi

# Create installation directory
echo "Creating installation directory at $INSTALL_DIR..."
sudo mkdir -p "$INSTALL_DIR" || { echo "Failed to create directory $INSTALL_DIR. Exiting..."; exit 1; }

# Copy files to the installation directory
echo "Copying files to $INSTALL_DIR..."
sudo cp -r bin dist resources LICENSE neutralino.config.json "$INSTALL_DIR/" || { echo "Failed to copy files. Exiting..."; exit 1; }

# Set permissions for the binary
echo "Setting permissions for the binary..."
sudo chmod +x "$INSTALL_DIR/bin/$BIN_FILE" || { echo "Failed to set permissions for $BIN_FILE. Exiting..."; exit 1; }

# Copy the icon to the appropriate directory
echo "Installing application icon..."
sudo mkdir -p "/usr/share/icons/hicolor/64x64/apps/"
sudo cp "$INSTALL_DIR/resources/icons/budget.png" "/usr/share/icons/hicolor/64x64/apps/$APP_NAME.png" || { echo "Failed to copy icon. Exiting..."; exit 1; }

# Create desktop entry file
cho "Creating desktop entry..."
cat > "/tmp/$APP_NAME.desktop" << EOF
[Desktop Entry]
Name=Budget Planner
Exec=$INSTALL_DIR/bin/$BIN_FILE --no-sandbox
Icon=/usr/share/icons/hicolor/64x64/apps/$APP_NAME.png
Type=Application
Categories=Office;Finance;
Version=1.0.0
Terminal=false
StartupNotify=true
StartupWMClass=budget
EOF

# Move desktop entry to the applications directory
echo "Installing desktop entry..."
sudo mv "/tmp/$APP_NAME.desktop" "$DESKTOP_ENTRY" || { echo "Failed to create desktop entry. Exiting..."; exit 1; }

# Update desktop database
echo "Updating desktop database..."
sudo update-desktop-database || { echo "Failed to update desktop database. Exiting..."; exit 1; }

echo "$APP_NAME installed successfully!"
