#!/usr/bin/bash

user=$4
display=$5

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
      sudo 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 --nogpgcheck 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"
su $user -c "DISPLAY=$display nohup drovio > /dev/null 2>&1"
