#!/bin/bash

# ensure chrome-sandbox has the correct permissions
echo "*** Running post-install script tp set chrome-sandbox permissions ***"
sudo chown root:root /opt/Zutacore/chrome-sandbox
sudo chmod 4755 /opt/Zutacore/chrome-sandbox

# create the hidden folder ~/.zutacore if it doesn't exist
# Ensure correct $HOME is used, even with sudo
USER_HOME=$(eval echo ~$SUDO_USER)

# Create the hidden folder ~/.zutacore if it doesn't exist
ZUTACORE_DIR="$USER_HOME/.zutacore"
echo "*** Ensuring $ZUTACORE_DIR directory exists ***"
if [ ! -d "$ZUTACORE_DIR" ]; then
  mkdir -p "$ZUTACORE_DIR"
  echo "Created directory: $ZUTACORE_DIR"
else
  echo "Directory $ZUTACORE_DIR already exists."
fi

# Ensure that the user owns the directory
echo "*** Changing ownership of the directory ***"
sudo chown -R $SUDO_USER:$SUDO_USER "$ZUTACORE_DIR"

# Copy the JAR file to the hidden directory
echo "*** Copying app.jar to $ZUTACORE_DIR ***"
sudo cp /opt/Zutacore/resources/app/resources/app.jar "$ZUTACORE_DIR/app.jar"
sudo chown -R $SUDO_USER:$SUDO_USER "$ZUTACORE_DIR/app.jar"


# Update the .desktop file to set the Path variable to ~/.zutacore
DESKTOP_FILE="/usr/share/applications/zutacore.desktop"

if [ -f "$DESKTOP_FILE" ]; then
  # Check if the Path line exists, and update or add it
  if grep -q "^Path=" "$DESKTOP_FILE"; then
    # If Path exists, replace it
    sudo sed -i "s|^Path=.*|Path=$USER_HOME/.zutacore|" "$DESKTOP_FILE"
    echo "Updated Path in .desktop file."
  else
    # If Path doesn't exist, add it at the end of the file
    sudo echo "Path=$USER_HOME/.zutacore" >> "$DESKTOP_FILE"
    echo "Added Path to .desktop file."
  fi
else
  echo "Error: .desktop file not found at $DESKTOP_FILE"
fi