#!/bin/sh -x

########################################################
# note to self..                                       #
#                                                      #
# Build script for Nvidia modules x86 & x86_64         #
#                                                      #
# copy build script and driver file to /tmp then run   #
# from /tmp                                            #
#                                                      #
# NOTE: It's better to boot to command line without    #
# X running or any other video drivers installed       #
# (remove Xorg-7.7* etc from onboot.lst)               #
# (downloaded but not installed and without            #
# starting X, then run this script                     #
#                                                      #
# if successfull allow Nvidia to update xorg.conf file #
# then startx                                          #
#                                                      #
# This script assumes home persistence for archive     #
# creation.                                            #
# create extension from nvidia_raw.tar or              #
# from manual nvidia.tar backup  (selecting " n " at   #
# prompt will create build dir backup)                 #
#                                                      #
# else save backup of Nvidia-Linux-xxx-xxx build dir   #
# manually check status of *.ko files                  #
#                                                      #
# /etc/X11/xorg.conf may not be required but if needed #
# (depends on Xorg version) create an xorg.conf        #
# file with "sudo Xorg -configure" and                 #
# copy /root/xorg.conf.new to /etc/X11/xorg.conf       #
# and make a backup                                    #
########################################################

. /etc/init.d/tc-functions
useBusybox


# src ftp://download.nvidia.com/XFree86/Linux-x86 
set +x

# ***EDIT VERSION AND FILE NAME ONLY IF NEEDED***
ver="xxx"


if [ $(find . -maxdepth 1 -iname "NVIDIA-Linux*" | wc -l) -gt 1 ] || \
[ $(find . -maxdepth 1 -iname "NVIDIA-Linux*" | wc -l) -lt 1 ]; then 
    echo "Check quantity of Nvidia downloads in this directory.."
    exit 0
fi

# detect architecture 
kerarch=$(uname -m)
kerbuild=$(uname -r) 
if [ "$kerarch" == x86_64 ]; then
  arch="x86_64"
else
  arch="x86"
fi

#detect driver version
NVSRC1=$(find . -maxdepth 1 -iname "NVIDIA-Linux*")
NVSRC=${NVSRC1#*/}

if [ "$ver" == xxx ]; then
echo -e "$NVSRC" 2>/dev/null | grep -o '[[:digit:]]*\.[[:digit:]]*' 2>/dev/null | sort -u | tail -1 >/tmp/NVversion
echo -e "$NVSRC" 2>/dev/null | grep -o '[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*' 2>/dev/null | sort -u | tail -1 >>/tmp/NVversion
sed -i 's/\.$//' /tmp/NVversion
ver=$(cat /tmp/NVversion | sort -u | tail -1)
#ver=${ver/%./}
fi

echo -e "\nMachine Architecture is: $arch"
echo -e "Nvidia driver file is: $NVSRC"
echo -e "Nvidia driver version is: $ver \n"

read -p " Enter to continue"

##******************************************
echo -e "\n\nFetching build dependencies... "
set -x
########################################################
# check if deps installed already,                     #
# if not then check if available locally & install,    #
# else download & install                              #
########################################################

tceinstalled="/usr/local/tce.installed"
tcepath="/etc/sysconfig/tcedir/optional"

deps="compiletc.tcz \
linux-kernel-sources-env.tcz \
Xorg-7.7-3d-dev.tcz \
graphics-${kerbuild}.tcz \
pkg-config.tcz \
xorg-server-dev.tcz \
squashfs-tools.tcz \
autoconf.tcz \
findutils.tcz \
procps-ng.tcz \
elfutils-dev.tcz \
bash.tcz"

for i in $deps ; do 

pkgname=${i%.*}

if [ ! -f ${tceinstalled}/"$pkgname" ]; then
	if [ -f ${tcepath}/"$i" ]; then
	  while [ ! -f ${tceinstalled}/"$pkgname" ]; do
	    tce-load -i "$pkgname"; sleep 0.5
	  done
	else
	    tce-load -wil "$pkgname"
	fi
fi
[ -f "${tceinstalled}/$pkgname" ] || echo "${RED}$i failed to load, exiting..${NORMAL}"
[ -f "${tceinstalled}/$pkgname" ] || exit 1
done

sleep 1
cd /tmp
##End of fetch deps
##******************************************

[ -e /lib/modules/${kerbuild}/build ] || cliorx linux-kernel-sources-env.sh

set -x
#pidof Xorg | xargs kill -9
#kill `pidof Xorg`
pkill Xorg

while [ -d /tmp/.X11-unix ]; do
sudo rm -rf /tmp/.X11-unix
done
while [ -f /tmp/.X0-lock ]; do
sudo rm -f /tmp/.X0-lock
done

cd /tmp

set +x; echo -e "\n\n ${BLUE}Export compiler flags... ${NORMAL}"; set -x
if [ "x$arch" == xx86_64 ]; then
# x86_64
echo "compile flags for $kerarch"
export CFLAGS="-mtune=generic -Os -pipe"
export CXXFLAGS="-mtune=generic -Os -pipe -fno-exceptions -fno-rtti"
else
# x86
echo "compile flags for $kerarch"
export CFLAGS="-march=i486 -mtune=i686 -Os -pipe"
export CXXFLAGS="-march=i486 -mtune=i686 -Os -pipe"
fi


sudo mkdir /etc/X11

echo $NVSRC

[ -f /tmp/$NVSRC ] || sudo find ~/ -name "$NVSRC" -type f -exec sh -c 'exec cp -f "$@" /tmp' X '{}' +
[ -f /tmp/$NVSRC ] || wget -c http://us.download.nvidia.com/XFree86/$NVSRC
[ -f /tmp/$NVSRC ] && sudo chmod +x /tmp/$NVSRC || exit 2


cd /tmp
sudo touch NOW
sleep 5

if [ x"$arch" == xx86_64 ]; then
  if [ ! -e /lib64 ]; then
	sudo ln -s /lib /lib64
  fi
fi

# Options
sudo ./$NVSRC --keep --accept-license --no-cc-version-check --no-drm
# sudo ./$NVSRC --keep --accept-license --no-cc-version-check
# sudo ./$NVSRC --keep --accept-license --no-cc-version-check --force-tls=classic 
# sudo ./$NVSRC --keep --accept-license 
# sudo ./$NVSRC --extract-only ; exit
# exit


echo "success??  answer y/n "
while read -r -n 1 -s yn; do
case $yn in
  y) 
    echo "OK "
    break
  ;;
  n) 
    [ -d "/tmp/${NVSRC%.*}" ] && tar -cvf nvidia.tar ${NVSRC%.*}
    [ -e /tmp/nvidia.tar ] && cp /tmp/nvidia.tar ~/nvidia.tar
    [ -e /etc/X11/xorg.conf ] && sudo cp /etc/X11/xorg.conf ~/xorg.conf
    [ -e ~/nvidia.tar ] || echo "build dir achive not saved "
    [ -e ~/xorg.conf ] || echo "xorg.conf not saved "
    sleep 15
    exit
  ;;
  *) 
    echo "invalid entry "
esac
done



sleep 1
sudo rm -f /usr/lib/libnvidia-tls.so.$ver

sudo nvidia-xconfig
sudo ldconfig
sudo depmod

## additional optional commands
[ -d /home/tc/nvidia_raw ] || mkdir -p /home/tc/nvidia_raw
sudo find /usr -newer /tmp/NOW -not -type d > /home/tc/nvidia_raw/nvidia_raw.list
sudo find /etc -newer /tmp/NOW -not -type d >> /home/tc/nvidia_raw/nvidia_raw.list
sudo find /lib -newer /tmp/NOW -not -type d | grep /lib/modules/${kerbuild}/kernel/drivers/ >> /home/tc/nvidia_raw/nvidia_raw.list
cd /home/tc/nvidia_raw
tar -T nvidia_raw.list -czvf nvidia_raw.tar.gz

cd /home/tc

#startx

exit
#mkdir -p /etc/X11
#nvidia-xconfig --force-generate
#sudo ln -s /lib/modules/${kerbuild}/kernel/drivers/video/nvidia.ko /usr/local/lib/xorg/modules/nvidia.ko




	




