#!/bin/sh
#setup_script
NASType=""
if [ "raspberrypi" = `uname -n` ]
then
### This is the Raspberry PI
	NASType="raspberrypi"
fi

if [ "$NASType" = "" ]
then
	echo "Unknown OS, please check your raspberry" 
	uname -a
	exit
fi

beta=0
if test $# -ge 1
	then
	    if [ $1 = "-b" ] 
	 		then
	 			beta=1
	 			echo "#####  Downloading from beta-directory"
	 		fi
fi

echo "#####  Install ThermIQ on Raspberry Pi ########################################"
echo $NASType

###############################################################################
# Install apache2 php5 msmtp sqlite
echo "#####  Install apache2 php5 msmtp sqlite ########################################"

echo ""
#http://www.deviousweb.com/index.php/blog/raspberry-pi/item/6-raspberry-pi-as-a-web-server-part-1-apache
ifconfig -a

apt-get -y update
apt-get -y dist-upgrade
apt-get -y install apache2
apt-get -y install libapache2-mod-php5 libapache2-mod-perl2 php5 php5-cli php5-cgi
apt-get -y install php5-common php5-curl php5-dev php5-gd 
apt-get -y install php5-imap php5-ldap php5-mhash php5-mysql php5-odbc 
apt-get -y install php5-sqlite   
apt-get -y install msmtp msmtp-mta ca-certificates
apt-get -y install picocom



# Set user groups
usermod -a -G www-data pi
usermod -a -G dialout www-data
usermod -a -G input www-data
usermod -a -G users www-data
echo "www-data ALL = (ALL) NOPASSWD: /usr/sbin/update_client_bin" >> /etc/sudoers.d/thermiq_update_client_bin
chmod 0440 /etc/sudoers.d/thermiq_update_client_bin
echo "www-data ALL = (ALL) NOPASSWD: /usr/sbin/update_client" >> /etc/sudoers.d/thermiq_update_client
chmod 0440 /etc/sudoers.d/thermiq_update_client
echo "www-data ALL = (ALL) NOPASSWD: /var/www/check_install.php" >> /etc/sudoers.d/check_install
chmod 0440 /etc/sudoers.d/check_install


# Fake path to php for scripts
mkdir /opt/bin
cd /opt/bin/
ln -s /usr/bin/php5 php
ln -s /bin/stty stty


###############################################################################
# Setup ThermIQ USB Device
echo "#####  USB Device ###############################################################"

#Add blacklist cdc_acm  to /etc/modprobe.d/blacklist.conf
sed -i 's:^blacklist cdc_acm.*::' /etc/modprobe.d/raspi-blacklist.conf
sed -i '/^$/d' /etc/modprobe.d/raspi-blacklist.conf
echo blacklist cdc_acm >> /etc/modprobe.d/raspi-blacklist.conf

modprobe usbserial vendor=0x4d8 product=0xfdeb
cd /etc/init.d/
echo '#!/bin/sh' > /etc/init.d/ThermIQ_Startup
echo '### BEGIN INIT INFO' >> /etc/init.d/ThermIQ_Startup
echo '# Provides: ThermIQ_Startup' >> /etc/init.d/ThermIQ_Startup
echo '# Required-Start: $all' >> /etc/init.d/ThermIQ_Startup
echo '# Required-Stop: ' >> /etc/init.d/ThermIQ_Startup
echo '# Default-Start: 2 3 4 5' >> /etc/init.d/ThermIQ_Startup
echo '# Default-Stop: 0 1 6' >> /etc/init.d/ThermIQ_Startup
echo '# Short-Description: ThermIQ_Startup' >> /etc/init.d/ThermIQ_Startup
echo '# Description: Init the ThermIQ usb port' >> /etc/init.d/ThermIQ_Startup
echo '### END INIT INFO' >> /etc/init.d/ThermIQ_Startup
echo 'chmod 777 /dev/ttyUSB0' >> /etc/init.d/ThermIQ_Startup
echo 'stty -F /dev/ttyUSB0 clocal cread -parenb -brkint -icrnl -imaxbel -opost -isig -icanon -iexten -echo time 25 min 0 9600' >> /etc/init.d/ThermIQ_Startup
echo '/usr/sbin/mkdbtemplate' >> /etc/init.d/ThermIQ_Startup	
chmod 755 /etc/init.d/ThermIQ_Startup
update-rc.d ThermIQ_Startup defaults  >> /dev/null

cd /etc/
sed -i 's:^.*vendor=0x04d8 product=0xfdeb.*::' /etc/modules
echo "usbserial vendor=0x04d8 product=0xfdeb" >> /etc/modules


###############################################################################
# Download ThermIQ files
echo "####  Download ThermIQ files     ################################################"
echo "Download ThermIQ files"
echo ""

cd /tmp/
rm -rf thermiq
mkdir thermiq
cd thermiq
rm -rf /tmp/thermiq/*

if [ $beta -eq 1 ]
then
	wget -T 900 -t 30 http://www.thermiq.net/ThermIQ_beta/thermiq_svn.tar.gz
else
	wget -T 900 -t 30 http://www.thermiq.net/ThermIQ_Client/thermiq_svn.tar.gz
fi

tar -xz -f thermiq_svn.tar.gz

if [ -d /tmp/thermiq/common ]; then
	echo "ThermIQ files downloaded OK"
	echo "Starting installation"
else 
 echo "ThermIQ files not found in /tmp/thermiq"
 echo "Check your internet connection etc"
 exit 1
fi
chown www-data:www-data /tmp/thermiq
chown -R www-data:www-data /tmp/thermiq/*
chmod 755 /tmp/thermiq/common/webcontent/php-ofc-library/*
chmod 755 /tmp/thermiq/common/usr/sbin/*

cd /var/www
rm -rf /var/www/index.*


#cp -fpr /tmp/thermiq/common/webcontent/html/img /var/www
#cp -fpr /tmp/thermiq/common/webcontent/html/img/* /var/www/img/
cp -fpr /tmp/thermiq/common/webcontent/html/* /var/www
cp -fpr /tmp/thermiq/common/webcontent/php-ofc-library /var

cp -fpr /tmp/thermiq/common/usr/sbin/* /usr/sbin/

mkdir /opt/etc
chown www-data /opt/etc 
chgrp www-data /opt/etc

# Save existing ini file
if [ -e /opt/etc/Thermiq_Linux.ini ]; then cp -f /opt/etc/Thermiq_Linux.ini /tmp/thermiq/common/opt/etc/
fi

mv /tmp/thermiq/common/opt/etc/* /opt/etc/

mv -f /tmp/thermiq/common/webcontent/init.php /var/


# Set paths needed for apache and php
# Apache needs module expire enabled
cd /etc/apache2/mods-available/
rm -f thermiq.conf

echo '<IfModule mod_expires.c>
 #Enable expiration per default
   ExpiresActive On
   ExpiresDefault A2592000
   Header append Cache-Control "public"
	<filesMatch "\.(php)$">
		ExpiresActive Off
	  FileETag None
	  <ifModule mod_headers.c>
	     Header unset ETag
	     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
	     Header set Pragma "no-cache"
	     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
	  </ifModule>
	</filesMatch>
 </ifModule>' >> thermiq.conf


cd /etc/apache2/mods-enabled/
ln -s ../mods-available/expires.load
ln -s ../mods-available/headers.load
ln -s ../mods-available/thermiq.conf

# Php
 
rm -f /etc/php5/conf.d/30-thermiq.ini
rm -f /tmp/30-thermiq.ini
echo 'include_path = ${include_path} ":.:/usr/share/php:/usr/share/pear:/usr/bin:/usr/sbin:/var/www"' > /tmp/30-thermiq.ini
echo 'sendmail_path = "/usr/bin/msmtp -C /etc/msmtprc -t"' >> /tmp/30-thermiq.ini
mv /tmp/30-thermiq.ini /etc/php5/conf.d/
chmod a+rx  /etc/php5/conf.d/30-thermiq.ini


mv -f /tmp/thermiq/RevisionLog.txt /
chmod 644 /RevisionLog.txt





# Make sure that php-scripts are found also by user www-data
sed -i 's:^.*php_scriptpath.*:php_scriptpath = /usr/sbin/:' /opt/etc/Thermiq_Linux.ini


	
cd /tmp/thermiq
cd /usr/sbin

################################################################################
# Database and paths
echo "#####  Database and paths   #####################################################"
echo "Database paths and paths"
echo ""
# Create basic structure, file linking is done each startup from script below
mkdir /var/sqlite
chown www-data:www-data /var/sqlite


chgrp -R www-data /var/sqlite
chmod -R g+rwx /var/sqlite
#change database paths in Thermiq_Linux.ini
sed -i 's:^tempdir.*:tempdir  = /var/sqlite/:' /opt/etc/Thermiq_Linux.ini
sed -i 's-^temporary.*-temporary  = sqlite:/var/sqlite/hptempdb-' /opt/etc/Thermiq_Linux.ini

# Create the permanent database if it doesnt exist
if [ -e /var/sqlite/hpdb ]; then
	echo "ThermIQ permanent database exists. No need to create a new"
else 
	echo "ThermIQ permanent database doesnt exists. Creating a new"
	/usr/sbin/new_db_sqlite
fi
/usr/sbin/mkdbtemplate
chown www-data:www-data /var/sqlite/*


################################################################################
# Add poller to the crontab
echo "#####  Add poller to the crontab ################################################"
cd /etc
sed -i 's:^.*/usr/sbin/poller.*::' /etc/crontab
echo "* * * * * www-data /usr/sbin/poller >/dev/null 2>&1" >> /etc/crontab

################################################################################
# Init setup of smtp transfer program esmtp
echo "#####  Init setup of smtp transfer program esmtp ################################"
echo "Init setup of smtp transfer program esmtp"
echo ""

sed -i 's:^.*mail_rc_file.*:mail_rc_file  = /etc/msmtprc:' /opt/etc/Thermiq_Linux.ini

cd /etc
if [ -e /etc/msmtprc ]; then
	echo "/etc/msmtprc exists. Mail-settings will be kept"
else
echo "account default" > /etc/msmtprc
echo "host smtp.isp.com" >> /etc/msmtprc
echo "port 25" >> /etc/msmtprc
echo "from me@isp.com" >> /etc/msmtprc
echo "auth on" >> /etc/msmtprc
echo "user myusername" >> /etc/msmtprc
echo "password secret" >> /etc/msmtprc

fi

chown www-data /etc/msmtprc
chgrp www-data /etc/msmtprc
chmod 600 /etc/msmtprc
touch /var/sqlite/mailargs


################################################################################
# Setup of Tellstick
#install tellstick sw guide from
#http://raspberry.arctics.se/2013/04/06/anvanda-en-tellstick-tillsammans-med-raspberry-pi/
echo "Do you want to install support for Tellstick DUO (Y/N)=?"
read str

if [ $str = "Y" ] || [ $str = "y" ] ; then
	echo "#####  Preparing Raspberry for Tellstick ################################"
	echo ""
	# Packages needed by Tellstick
	apt-get -y install libftdi1 libftdi-dev
	apt-get -y install libconfuse0 libconfuse-dev
	apt-get -y install cmake
	# Install driver needed for tellstick
	modprobe ftdi_sio vendor=0x1781 product=0x0c30
	
	#add this line /etc/modules
	#ftdi_sio vendor=0x1781 product=0x0c30
	cd /etc/
	sed -i 's:^.*vendor=0x1781 product=0x0c30.*::' /etc/modules
	echo "ftdi_sio vendor=0x1781 product=0x0c30" >> /etc/modules
	
	cd /tmp
	wget http://download.telldus.se/TellStick/Software/telldus-core/telldus-core-2.1.1.tar.gz
	tar xfz telldus-core-2.1.1.tar.gz
	cd telldus-core-2.1.1/
	cmake .
	make
	make install
	ldconfig
	
	#daemon file
	mv -f /tmp/thermiq/pkg_raspberry/telldusd /etc/init.d/
	chmod +x /etc/init.d/telldusd
	update-rc.d telldusd defaults
	service telldusd restart
fi

echo "#####  Done ! ################################"
