#!/bin/sh
# bumblebee.sh
# 2016-08-01

# Bumblebee - NVIDIA Optimus support for Linux
# http://docs.slackware.com/howtos:hardware:nvidia_optimus

# exit on error
set -e

SLACKVER=$(awk '{print $2}' /etc/slackware-version)

REPO="https://github.com/WhiteWolf1776/Bumblebee-SlackBuilds.git"
if [ "$SLACKVER" = "14.0" ]; then
  REPO="https://github.com/jgeboski/Bumblebee-SlackBuilds.git"
fi

if [ ! -d Bumblebee-SlackBuilds ]; then
  git clone "$REPO"
fi
cd Bumblebee-SlackBuilds
if [ "$SLACKVER" = "14.1" ]; then
  git checkout 14.1
else
  git checkout master
fi
git pull
echo "Press Enter to continue or CTRL-C to cancel."
read CONTINUE

DIR=$(pwd)

./download.sh

# http://slackbuilds.org/uid_gid.txt
if [ "$(grep bumblebee /etc/group)" = "" ]; then
  groupadd -g 261 bumblebee
fi

if [ ! -f /etc/modprobe.d/BLACKLIST-nouveau.conf ]; then
  cat > /etc/modprobe.d/BLACKLIST-nouveau.conf <<EOF
# Do not load the kernel nouveau dri module, since it interferes with both
# the nv and binary nvidia drivers.

blacklist nouveau

EOF
fi

if [ ! -f /etc/modprobe.d/bbswitch.conf ]; then
  cat > /etc/modprobe.d/bbswitch.conf <<EOF
# Disable card on boot
blacklist nvidia
blacklist nvidia_drm
blacklist nvidia_modeset
blacklist nouveau
options bbswitch load_state=0
EOF
fi

PKGS="libbsd bumblebee bbswitch"
if [ "$SLACKVER" = "14.0" -o "$SLACKVER" = "14.1" ]; then
  PKGS="$PKGS libvdpau"
fi
PKGS="$PKGS nvidia-kernel nvidia-bumblebee"
if [ "$SLACKVER" = "14.0" ]; then
  PKGS="$PKGS libjpeg-turbo VirtualGL"
else
  PKGS="$PKGS primus"
fi
for PKG in $PKGS; do
  cd "$DIR/$PKG"
  COMPAT32=yes ./$PKG.SlackBuild || exit 1
  NEWEST=$(ls -rv /tmp/$PKG-*.t?z | head -n1)
  upgradepkg --install-new --reinstall $NEWEST
done

chmod +x /etc/rc.d/rc.bumblebeed

if [ "$(grep bumblebee /etc/rc.d/rc.local)" = "" ]; then
  cat >> /etc/rc.d/rc.local << EOF
if [ -x /etc/rc.d/rc.bumblebeed ]; then
  /etc/rc.d/rc.bumblebeed start
fi
EOF
fi

if [ ! -f /etc/rc.d/rc.local_shutdown ]; then
  cat >> /etc/rc.d/rc.local_shutdown << EOF
#!/bin/sh
EOF
  chmod +x /etc/rc.d/rc.local_shutdown
fi

if [ "$(grep bumblebee /etc/rc.d/rc.local_shutdown)" = "" ]; then
  cat >> /etc/rc.d/rc.local_shutdown << EOF
if [ -x /etc/rc.d/rc.bumblebeed ]; then
  /etc/rc.d/rc.bumblebeed stop
fi
EOF
fi