#!/bin/bash

echo " "
echo "Install script for AMD Geode framebuffer driver version 2.7.14"

# Global variables .....
max_num=0
num=1
file_list="fbmem.c fbgen.c Makefile Config.in nsc"
driver_dir="/drivers/video/"


find_index(){ 
    fbcurrent=$1
    if [ -e $fbcurrent ] ; then
	 num=1
	 flag=0
	 while [ $flag -eq 0 ] ; do 
	    destination="${fbcurrent}.${num}"
	    if [ ! -e $destination ]  ; then
		    flag=1
	    else
		    num=`expr $num + 1`
	    fi
	 done
	 export num
    fi
}

mv_file() {
	fbcurrent=$1
	if [ -e $fbcurrent ] ; then
		destination="${fbcurrent}.${max_num}"
		echo "mv $fbcurrent $destination"
		mv $fbcurrent $destination
	fi
}

max_index() {

	if [ $num -gt $max_num ] ;  then
		max_num=$num
	fi
}
find_version() {

	data=`head -3 $1 | cut -d " " -f 3`
	loopndx=0
	kernel_ver=

	for var in $data ; do
		loopndx=`expr $loopndx + 1`
		if [ $loopndx -eq 3 ] ;then
    			kernel_ver="${kernel_ver}`echo -en $var`"
		else
			kernel_ver="${kernel_ver}`echo -en $var\.`"
    		fi
	done
	export kernel_ver
}

echo " "
echo "ls -l /usr/src"
ls -l /usr/src
echo " "
echo "Enter the linux kernel complete source path (default is /usr/src/linux)"
read linux_path
if [ -z $linux_path ] ; then
        linux_path="/usr/src/linux"
fi
if [ ! -d ${linux_path} ] ; then
	echo "$linux_path does not exist!"
	echo " "
	exit
fi


bell=0

linux_version="${linux_path}/Makefile"
if [ -f $linux_version ] ; then
   find_version $linux_version
   echo "$linux_path has linux $kernel_ver version "
   echo -en "Do you want to continue (y/n)? "
   read bell
   if [ $bell != 'y' -a $bell != 'Y' ] ; then
	exit
   fi

else 
  echo "$linux_path is not a linux source tree!"
  exit

fi

#
# Get the max backup revision (have to scan whole list)
for file in $file_list ; do
	find_index "${linux_path}${driver_dir}${file}"
	max_index
done

#
# Backup and install files
for file in $file_list ; do
	cp_opt=""
	if [ -d $file ] ; then
		cp_opt="-r"
	fi	
	mv_file "${linux_path}${driver_dir}${file}"
	echo "cp $cp_opt $file ${linux_path}${driver_dir}"
	cp $cp_opt $file "${linux_path}${driver_dir}"
done

