#!/bin/bash
set -e

if [ `whoami` != root ]; then
    echo "Please run this script as root or using sudo!"
    exit
fi

lines=50
program=wlanthermo

echo "Check Ramdrive and create it if it doesn't exist"
RD=$(cat /etc/fstab|grep /var/www/tmp|grep -v grep|wc -l)

if  [ $RD == 0 ]; then
  mkdir /var/www/tmp -p
  mount -t tmpfs -o size=16M,mode=770,uid=www-data,gid=www-data tmpfs /var/www/tmp
  echo "tmpfs           /var/www/tmp    tmpfs   size=16M,mode=770,uid=www-data,gid=www-data     0       0" >> /etc/fstab
  echo "RAM Drive created!"
fi
if  [ $RD != 0 ]; then
  echo "RAM Drive already exists"
fi

echo "Install depencies:"
aptitude install gnuplot lighttpd apache2-utils python-dev php5-cgi php5-gd python2.7-pyinotify sudo python-psutil vim htop php5-curl iftop iotop python-urllib3 fswebcam -y

echo "add / modify sudoers entrys"
SU=$(cat /etc/sudoers|grep 'www-data ALL='|wc -l)
sud="www-data ALL=(ALL) NOPASSWD:/sbin/ifdown wlan0,/sbin/ifup wlan0,/bin/cat /etc/wpa_supplicant/wpa_supplicant.conf,/bin/cp /tmp/wifidata /etc/wpa_supplicant/wpa_supplicant.conf,/sbin/wpa_cli scan_results,/sbin/wpa_cli scan,/bin/cp,/bin/sleep,/bin/ps,/usr/bin/fswebcam,/usr/bin/raspi_webcam.sh,/tmp/WLANThermo_install.run"
if [ $SU == 0 ];then
    echo $sud >> /etc/sudoers
else
    sed -i -e "s|www-data ALL=.*|${sud}|g" /etc/sudoers
fi
service sudo restart

echo "Extract the package"
tail -n +$lines $0 > /tmp/${program}.deb
sleep 2
echo 'install /tmp/${programm}.deb'
dpkg -i /tmp/${program}.deb

url=$(cat /etc/hostname)
echo " "
echo "========***********WLANThermo installed completely open http://$url in a browser! ***********==========="
echo " "

exit 0
