#!/bin/bash
# Fetch and install nvidia drivers from Ubuntu xorg-edgers PPA archive
# Copyright 2015 TJ <ubuntu@iam.tj>
# Licensed on the terms of the GNU General Public License version 3

PKG=${PKG:-nvidia-graphics-drivers}
PKG_SETTINGS=${PKG_SETTINGS:-nvidia-settings}
PPA_URL=${PPA_URL:-http://ppa.launchpad.net/xorg-edgers/ppa/ubuntu/pool/main/n}
ARCH=$(dpkg --print-architecture)
RELEASE=$(lsb_release -sr)

if [ -z "${RELEASE}" ]; then
  echo "Error: could not determine which release this is, please enter it manually in the form YY.MM e.g. 14.04 :"
  read RELEASE
fi 

if ! dpkg -l dkms | grep '^ii' ; then
  echo "Info: Need to pre-install the Dynamic Kernel Module Support (DKMS) first"
  sudo apt-get install dkms
fi

# get list of directories from the archive HTTP server
DIRS=$(wget -q -O - $PPA_URL | grep '[DIR]' | sed -n 's/.*a href="\(.*\)">'${PKG}'.*/\1/p' )

# separate the version numbers from the directory paths
VERSIONS=""
for V in $DIRS; do V2=${V##*-}; VERSIONS="${VERSIONS} ${V2%%/*}"; done

if [ -z "${VERSIONS}" ]; then
  echo "No $PKG versions found at $PPA_URL"
  exit 1
fi

# ask the user which version is to be fetched
echo "$PKG versions available: ${VERSIONS}"
echo "Please enter the version you require: "
read VERSION

if ! echo "${VERSIONS}" | grep -q "${VERSION}" ; then
  echo "Error: do not recognise version"
  exit 2
fi

# build list of binary packages for this architecture and release
PACKAGES=$(wget -q -O - "${PPA_URL}/${PKG}-${VERSION}" | sed -n 's/.*a href="\(.*'${RELEASE}'[0-9.]*_'${ARCH}'\.deb\)".*/\1/p')

# do the download in a temporary directory
pushd /tmp >/dev/null
mkdir -p "${PKG}/${VERSION}"
cd "$PKG/${VERSION}"

PKG_LIST=""
for P in $PACKAGES; do
  echo "Fetching package ${P} ..."
  wget -nc  "${PPA_URL}/${PKG}-${VERSION}/${P}"
  if echo "${P}" | grep -qv '\-dev_' ; then
    PKG_LIST="${PKG_LIST} $P"
  fi
done

# build list of binary packages for the settings utility
SETTER=$( wget -q -O - "${PPA_URL}/${PKG_SETTINGS}" | sed -n 's/.*a href="\(.*'${RELEASE}'.*_'${ARCH}'\.deb\)">.*/\1/p' )
echo "${PKG_SETTINGS} = ${SETTER}"

for P in ${SETTER}; do
  echo "Fetching package ${P} ..."
  wget -nc "${PPA_URL}/${PKG_SETTINGS}/${P}"
  if echo "${P}" | grep -qv '\-dev_' ; then
    PKG_LIST="${PKG_LIST} ${P}"
  fi
done

# List the packages to be installed
echo "Beginning to install the following packages for ${RELEASE} ${ARCH} ${PKG}-${VERSION} and ${PKG_SETTINGS}"
echo
for P in ${PKG_LIST}; do
  echo ${P}
done

echo
echo "Is this what you want (N/y) ?"
read ANSWER

if [ "x${ANSWER}" = "xy" -o "x${ANSWER}" = "xY" ]; then
  sudo dpkg -i ${PKG_LIST}
fi

popd >/dev/null

# check whether this looks like an Optimus hybrid dual GPU system (GPUs from different manufacturers)
PRIME="$(lspci -nn | grep VGA | grep -v NVIDIA)"
if [ -n "${PRIME}" ]; then
  echo "If the system contains multiple GPUs from different manufacturers (Optimus) please also do"
  echo "sudo apt-get install nvidia-prime"
  lspci -nn | grep VGA
fi

