#!/bin/bash


ROOT_UID=0         # Root has $UID 0.
if [ "$UID" -ne "$ROOT_UID" ]
then
  echo; echo "Only root can run this script."; echo
  exit 65
fi

pid=`less /var/run/SysRam.pid 2>&1`
fnd=`expr index "$pid" 'No such file or directory'`
wheel=0
c=("-" "\\" "|" "/")

if [ $fnd -eq 0 ];
then
	echo -ne "\n\nremoving SysRam-Disks:   "
	kill -SIGUSR1 $pid
	if [ $? -eq 0 ];
	then
		while [[ -e "/var/run/SysRam.pid" ]];
		do
			usleep 300
			(( x=$((wheel++))%4))
			echo -ne "\b${c[$x]}"
		done
		echo -e "\b.. done, check (df -a):"
		sleep 1;
		df -a
		exit 0
	fi
fi

echo -e "\ncould\'t kill rmSysRam, do it myself.."

# dele SysRam and restore original System:
tme=`date`
echo
echo "removing /var /etc und /tmp from RAM at $tme.."
echo "removing /var /etc und /tmp from RAM at $tme.."  >>/var/log/SysRam.log

# stop syslog to give it a chance to write and close open file handles..
/etc/init.d/./syslog stop  >>/var/log/SysRam.log 2>&1

# umount sequnce: /var, /etc /tmp (the other way we've mounted!)
umount -vl /var
echo "umount /var : $?  ( 0 = ok )" >>/var/log/SysRam.log
echo "umount /var : $?  ( 0 = ok )"
cd /rVar
rtn=`find . -depth -print0 | cpio -p0dvm /var 2>&1`
echo -n "."
umount -vl /rVar
echo "umount /rVar: $?  ( 0 = ok )" >>/var/log/SysRam.log
echo "umount /rVar: $?  ( 0 = ok )"

# /etc and correct mtab
umount -vl /etc
echo "umount /etc : $?  ( 0 = ok )" >>/var/log/SysRam.log
echo "umount /etc : $?  ( 0 = ok )"
umount -vl /rEtc
echo "umount /rEtc: $?  ( 0 = ok )" >>/var/log/SysRam.log
echo "umount /rEtc: $?  ( 0 = ok )"
# /tmp do not correct mtab, it is not written there!!
umount -vl /tmp
echo "umount /tmp : $?  ( 0 = ok )" >>/var/log/SysRam.log
echo "umount /tmp : $?  ( 0 = ok )"
umount -vl /rTmp
echo "umount /rTmp : $?  ( 0 = ok )" >>/var/log/SysRam.log
echo "umount /rTmp : $?  ( 0 = ok )"


echo
echo -n "now restart services from init 3: "

echo "now restart services from init 3: " >>"/var/log/SysRam.log"
cd /etc/init.d/rc3.d/
for file in $( find . -type l -name '*' | sort )
do
	KS=${file:2:1}
	name=${file:5}
	# exclude from restart
	if [ $name = 'network' -o $name = 'nfsserver' -o $name = 'random' -o $name = 'alsasound' -o $name = 'nfslock' -o $name = 'portmap' -o $name = 'sshd' -o $name = 'random' ];
	then
		continue
	fi
	# use the sequence of start in init.d/rc3.d
	if [ $KS = 'S' ]; # Start-Sequence
	then
		echo -e "\n$name \t restart .." >>"/var/log/SysRam.log"
		/etc/init.d/./$name restart >>"/var/log/SysRam.log" 2>&1
		echo -n "."
	else
		continue
	fi
done
echo  " done, check:" >>"/var/log/SysRam.log"
echo  " done, check (df -a):"

echo

df=`df -a`
echo -e "$df \n \n##############  ready  ###############"  >>"/var/log/SysRam.log"
echo "$df"
echo

exit 0
