#!/bin/bash

# Script to manage super user commands

# Default arguments
MOUSE="false"
OPTIMIZE="false"

# Function to display usage
usage() {
    echo "Usage: $0 [mouse|optimize|setupall]"
    exit 1
}

# Ensure the user passed a parameter
if [ -z "$1" ]; then
    usage
fi

# Handle script options
case "$1" in
  mouse)
    MOUSE="true"
    shift
    while [ $# -gt 0 ]; do
      case $1 in
        *)
          echo "Unknown arg $1"
          exit 1
          ;;
      esac
    done
    ;;
  optimize)
    OPTIMIZE="true"
    shift
    while [ $# -gt 0 ]; do
      case $1 in
        *)
          echo "Unknown arg $1"
          exit 1
          ;;
      esac
    done
    ;;
  setupall)
    MOUSE="true"
    OPTIMIZE="true"
    shift
    while [ $# -gt 0 ]; do
      case $1 in
        *)
          echo "Unknown arg $1"
          exit 1
          ;;
      esac
    done
    ;;
  *)
    echo "Unknown arg $1"
    exit 1
    ;;
esac


# Mouse
if [ $MOUSE = "true" ] ; then
  echo "Configuring mouse idle behavior..."
  # Unclutter installation confirmation
  if ! command -v unclutter > /dev/null; then
    echo "Unclutter not found. Installing..."
    sudo apt-get install unclutter -y
  else
    echo "Unclutter is already installed."
  fi
  # Unclutter setup in system autostart
  if ! grep -q "^@unclutter -idle 1" "/etc/xdg/lxsession/LXDE-pi/autostart"; then
    sudo sh -c "echo '@unclutter -idle 1' >> /etc/xdg/lxsession/LXDE-pi/autostart"
    echo "Unclutter command added to autostart. Restart device to complete installation"
  else
    echo "Unclutter command already exists in autostart."
  fi
  if [ $OPTIMIZE = "false" ] ; then
    exit 0
  fi
fi

# Optimize
if [ $OPTIMIZE = "true" ] ; then
  echo "Optimizing system autostart configuration..."
  AUTOSTART_DIR="/etc/xdg/autostart"
  BACKUP_DIR="/etc/xdg/backup"
  [ ! -d "$BACKUP_DIR" ] && sudo mkdir -p "$BACKUP_DIR" && echo "Created backup directory: $BACKUP_DIR"
  FILES_TO_MOVE=("xcompmgr.desktop" "print-applet.desktop" "squeekboard.desktop" "xdg-user-dirs.desktop" "xdg-user-dirs-kde.desktop")
  for FILE in "${FILES_TO_MOVE[@]}"; do
    if [ -f "$AUTOSTART_DIR/$FILE" ]; then
      sudo mv "$AUTOSTART_DIR/$FILE" "$BACKUP_DIR/"
      echo "Moved $FILE to backup directory."
    else
      echo "File not found: $FILE (skipped)."
    fi
  done
  if [ $MOUSE = "false" ] ; then
    echo "Optimization complete. Restart device to complete installation"
    exit 0
  fi
fi
echo "Setup complete, restart device to complete installation."
