#!/bin/sh
root=$(dirname $0 2>/dev/null)
sudo=$(which sudo 2>/dev/null)
whoami=$(whoami 2>/dev/null)
arch=$(uname -i 2>/dev/null)
dpkg=$(which dpkg 2>/dev/null)
rpm=$(which rpm 2>/dev/null)

addonsInstallCommand=''
installCommand=''

if ( [ "$sudo" = '' ] && [ "$whoami" != 'root' ] ); then
  echo "Unable to install unless you are root, or 'sudo' is available in your PATH"
  exit 1
fi
if [ "$arch" = 'unknown' ]; then
  arch=$(uname -m 2>/dev/null)
fi
if ( [ "$arch" = 'ppc64le' ] || [ "$arch" = 'ppc64el' ] ); then
  #Litte Endian
  ID_LIKE=''
  if   grep -iE '^ID(_LIKE)?=' /etc/os-release 2>/dev/null | grep -iE 'ubuntu|debian' >/dev/null 2>&1; then
    ID_LIKE='ubuntu'
  elif grep -iE '^ID(_LIKE)?=' /etc/os-release 2>/dev/null | grep -iE 'sles|suse' >/dev/null 2>&1; then
    ID_LIKE='sles'
  elif grep -iE '^ID(_LIKE)?=' /etc/os-release 2>/dev/null | grep -iE 'rhel|fedora|centos' >/dev/null 2>&1; then
    ID_LIKE='rhel'
  elif [ "$dpkg" != '' ]; then
    ID_LIKE='ubuntu'
  elif [ "$rpm" != '' ]; then
    ID_LIKE='rhel'
  fi

  if [ "$ID_LIKE" = 'ubuntu' ]; then
    installCommand="$sudo dpkg -iG $root/images/ubuntu/*.deb"
  elif [ "$ID_LIKE" = 'sles' ]; then
    installCommand="for pkg in \$(ls $root/images/sles/libxl*.rpm $root/images/sles/lib*.rpm); do $sudo rpm -Uvh \$pkg; done"
    addons=$(ls $root/images/sles/*devel*.rpm 2>/dev/null)
    if [ "$addons" != '' ]; then
      addonsInstallCommand="for pkg in \$(ls $root/images/sles/*devel*.rpm); do $sudo rpm -Uvh \$pkg; done"
    fi
  elif [ "$ID_LIKE" = 'rhel' ]; then
#    installCommand="for pkg in \$(ls $root/images/rhel/libxl[cf]-[0-9]*.rpm $root/images/rhel/libxlsmp-[0-9]*.rpm); do $sudo rpm -Uvh \$pkg; done"
    installCommand="for pkg in \$(ls $root/images/rhel/lib*.rpm); do $sudo rpm -Uvh \$pkg; done"
    addons=$(ls $root/images/rhel/*devel*.rpm 2>/dev/null)
    if [ "$addons" != '' ]; then
      addonsInstallCommand="for pkg in \$(ls $root/images/rhel/*devel*.rpm); do $sudo rpm -Uvh \$pkg; done"
    fi
  fi
fi
  
if [ "$installCommand" = '' ]; then
  echo 'Unable to determine the installation command based on the architecture and distribution'
  echo 'See the README for more information, or install manually from images'
  exit 1
fi

echo "$installCommand"
eval "$installCommand"

if [ "$addonsInstallCommand" != '' ]; then
  echo "$addonsInstallCommand"
  eval "$addonsInstallCommand"
fi
