#!/bin/bash

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

# Detect OS
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS_NAME=$ID
    OS_VERSION=$VERSION_ID
else
    echo -e "${YELLOW}Unable to detect OS, assuming Debian/Ubuntu...${NC}"
    OS_NAME="ubuntu"
fi

# Function to determine the package manager to use
determine_pkg_manager() {
  if command -v nala &> /dev/null; then
    echo "nala"
  elif [ "$OS_NAME" = "fedora" ]; then
    echo "dnf"
  else
    echo "apt"
  fi
}

PKG_MANAGER=$(determine_pkg_manager)
echo -e "${GREEN}Using package manager: $PKG_MANAGER${NC}"

# checks if the plexmediaserver.service is defined on this machine. stop it if it is.
if systemctl is-active --quiet plexmediaserver.service 2>/dev/null; then
  sudo /home/acedanger/shell/plex/plex.sh stop
fi

omz_upgrade_script=~/.oh-my-zsh/tools/upgrade.sh

# Check if the script exists and is executable
if [ -x "$omz_upgrade_script" ]; then
  echo -e "${YELLOW}Attempting Oh My Zsh upgrade...${NC}"
  "$omz_upgrade_script"
fi

# Update packages using the appropriate package manager
case $PKG_MANAGER in
  nala)
    echo -e "${GREEN}Updating system using nala...${NC}"
    sudo nala update
    sudo nala upgrade -y
    ;;
  dnf)
    echo -e "${GREEN}Updating system using dnf...${NC}"
    sudo dnf check-update -y || true
    sudo dnf upgrade -y
    ;;
  apt)
    echo -e "${GREEN}Updating system using apt...${NC}"
    sudo apt update
    sudo apt upgrade -y
    ;;
esac

# checks if the plexmediaserver.service is defined on this machine. start it if it is.
if systemctl is-enabled --quiet plexmediaserver.service 2>/dev/null; then
  sudo /home/acedanger/shell/plex/plex.sh start
fi
