#!/usr/bin/bash

user=$4
display=$5

# Run as root: drovio-updater checks both, and so does this script
if ! id -u -- "$user" > /dev/null 2>&1 || [[ ! "$display" =~ ^:[0-9]+(\.[0-9]+)?$ ]]; then
  echo "Invalid user or display"
  exit 1
fi

echo "Starting installation of $1. The app will be restarted for user $user on display $display"

auto=0
if [ "$3" == "--auto" ]; then
  auto=1
fi

ask_to_press_key() {
  if [ $auto -eq 0 ]; then
    echo $1
    read -n 1
  fi
}

# Installing package
echo "Installing new release..."
case $2 in
  "DEB")
    if type "/usr/bin/apt-get" > /dev/null; then
      /usr/bin/apt-get update
      /usr/bin/apt-get install -y "$1"
    else
      dpkg -i "$1"
    fi
    if [ ! $? -eq 0 ]; then
      echo "Package installation failed"
      ask_to_press_key "Press any key to exit..."
      exit 0
    fi
    ;;
  "RPM")
    if type "/usr/bin/yum" > /dev/null; then
      # yum sync with depos automatically
      /usr/bin/yum -y localinstall "$1"
    else
      rpm -U "$1"
    fi
    if [ ! $? -eq 0 ]; then
      echo "Package installation failed"
      ask_to_press_key "Press any key to exit..."
      exit 0
    fi
    ;;
  "ARCH")
    /usr/bin/pacman -Sy
    /usr/bin/pacman --noconfirm -U "$1"
    if [ ! $? -eq 0 ]; then
      echo "Package installation failed"
      ask_to_press_key "Press any key to exit..."
      exit 0
    fi
    ;;
  *)
    echo "Unknown package type"
    exit 0
    ;;
esac

echo "The new release has been succesfully installed on your system."
ask_to_press_key "Press any key to start Drovio..."

# Re-starting drovio app
echo "Restarting the app as : $user"
runuser -u "$user" -- env DISPLAY="$display" nohup drovio-launcher > /dev/null 2>&1
