#$Id: makefile,v 1.174 2015/11/06 11:09:53 sqko Exp $
httpd_conf := $(shell locate httpd.conf | grep -P '.conf$$')
html := /home/http/html/
cgi := /home/http/cgi-bin/
user := $(shell grep -P '^User' $(httpd_conf) | perl -e 'while ($$v = <>){chomp $$v; $$v =~ /(\w+)$$/; print $$1};')
group := $(shell grep -P '^Group' $(httpd_conf) | perl -e 'while ($$v = <>){chomp $$v; $$v =~ /(\w+)$$/; print $$1};')
libdir := $(shell locate CGI.pm | grep perl | perl -e 'while (<>){if(/(.*)\/CGI.pm/){print $$1;exit;}}')
path_TCP_pm := $(shell locate /Modbus/Transport/TCP.pm | grep /usr/ | grep -P '.pm$$')

LIBS := Debug.pm SemaforeFile.pm ElchemeaConfig.pm SocketClient.pm LATEX.pm
RFC := Observer.pm BaseDevice.pm BaseRelay.pm Header.pm Rig.pm Device.pm Main.pm MFC.pm Simple.pm Water.pm Multiplex.pm Templog.pm Gas.pm GasGroup.pm PSU.pm RFCCGI.pm AnalogOut.pm TempControl.pm Elektro.pm Honeywell.pm CGas.pm PSU_Bipolar.pm PSU_B2N.pm Monostable.pm Filter.pm SPDEV.pm PLC.pm PLCRead.pm PID.pm RFCPID.pm Cache.pm Kepco.pm PSUMulti.pm MKS.pm Spline.pm Ysplit.pm Logic.pm Sum.pm Pcontrol.pm Typecast.pm Alert.pm Math.pm Visitor.pm OmronTemp.pm
DEVS := Eurotherm.pm 

SUBDIRS := spline ch4_args OCV_corr tescom_crc omron_crc

# BINFILES is files which must have a symlink in /usr/local/bin
BINFILES := logfile.pl CGI-server gas.pl serial-socket-server-9.0.pl set_current set_voltage CGI_client.pl water.pl logfile.pl iV_curve.pl vogt.pl H2vogt.pl serial-socket-client-1.2.pl cnv.pl set_finish mail_errors.pl history-plot-electrode-1.0.pl history-plot-3.0.pl impedance_html.pl hio_korr test_rig_conf.pl format_jdata.pl make_latex_report remake_latex_report get_impedance_data potentiostat.pl custom_prog.pl plotall.pl impedance_plot.pl get_all_impedance CH4_vogt.pl indhold copyplot.pl plot_leak.pl jdata.pl make_report report-client iv1.pl

version := $(shell perl get_version.pl)
dist_version := $(shell perl -e 'use RFC::Header; print $$RFC::Header::VERSION')

.PHONY: libs uninstall dist log CPAN test clean p2c RFClibs /home/celltest/info_table.txt

all:
	@echo ""
	@echo ""
	@echo "    Risoe Fuel Cell control installer"
	@echo ""
	@echo ""
	@for i in $(SUBDIRS); do \
		echo "make all in $$i..."; \
		(cd $$i; $(MAKE) $(MFLAGS) $(MYMAKEFLAGS) all); \
	done
	@echo "If ch4_args fails to compile, run 'make p2c' as root to install the pascal to c converter (RPM's included)"
	@echo ""
	@echo ""
	@echo "Web server user and group is (according to $(httpd_conf)):"
	@echo "user: $(user)"
	@echo "group: $(group)"
	@echo "Document root must be: $(html)"
	@echo "CGI script dir must be: $(cgi)"
	@echo "make install will install files in the following directories:"
	@echo "$(cgi)/celltest/"
	@echo "$(html)/celltest/"
	@echo "/home/celltest/"
	@echo "/usr/local/bin/celltest/"
	@echo ""
	@echo ""
	@echo "        !   !   !   !    README  !    !    !    !"
	@echo ""
	@echo ""
	@echo "RFC control requires a number of CPAN Perl modules to be installed on the target system"
	@echo "The modules will be installed automatically when running 'make install', but make sure"
	@echo "that an active conection to the internet exists so that the modules can be downloaded"
	@echo "from CPAN.org. The modules can be installed separatly by running 'make CPAN'."
	@echo ""
	@echo ""
	@echo "Also remember to add all rig users to group $(group)!"
	@echo "If this group is not the intended group (for instance the $(group) group may have insuficient"
	@echo "premissions for normal operation), add the web server to a more appropriate group and rerun make."
	@echo "Notice that this sould be done BEFORE running make install!"
	@echo "New rigs can be added to the system by running ./create_rig.pl as root with the rig number as argument"
	@echo "If so, the group membership of the rig user will be set automatically when the resulting INSTALL_RIG"
	@echo "script is run!"
	@echo ""
	@echo ""
	@echo "Nothing more to do here, run 'make CPAN' followed by 'make test' followed by 'make install' as root!"
	@echo "Make CPAN is nescesarry to download and install the Perl modules required by the dependencies before make test"
	@echo "can be run"
	@echo "If make test fails, the likely cause is a configuration error for one or more"
	@echo "of the rigs on the system, refer the test log to find the offending configuration"
	@echo "and fix this as RFCControl can only install/upgrade on a system with no configuration errors!"
	@echo "(This is in order to make sure that no rig configurations are broken by installation"
	@echo "upgrades, either manual or automatic)"
	@echo ""
	@echo ""
	@echo "If database datamining is to be used (by running the load_test_data_db.pl script in /usr/local/bin/celltest)"
	@echo "make sure that the 'make db' command is run also. This can only run if the postgresql database is"
	@echo "installed on the target system (yum install postgresql-server, yum install postgresql-devel to install)"
	@echo "However this can not be automated as if postgresql is already installed, any upgrades can irreversibly damage"
	@echo "the runing postgresql service crashing the database!, thus you have to install/upgrade postgresql manually!"
	@echo "Notice, that this database upload functionality only works in conjunction with a Risoe Fuel cells and solid"
	@echo "state chemistry division Labsystem database version 2.1.10 or above with installed celltest datamining database!"
	@echo "Note that the database integration can only be installed after a complete installation of RFCcontrol!"

db:
	perl -MCPAN -e 'install DBI'
	perl -MCPAN -e 'install DBD::Pg'
	cp -R dbload/* /usr/local/bin/celltest/
	./set_db.pl

CPAN:
	perl -MCPAN -e 'install Test::Inter'
	perl -MCPAN -e 'install Encode::Locale'
	perl -MCPAN -e 'install IO::HTML'
	perl -MCPAN -e 'install Clone'
	perl -MCPAN -e 'install HTML::Parser'
	perl -MCPAN -e 'install HTTP::Config'
	perl -MCPAN -e 'install File::ReadBackwards'
	perl -MCPAN -e 'install Device::SerialPort'
	perl -MCPAN -e 'install IO::Interface'
	perl -MCPAN -e 'install Mail::Send'
	perl -MCPAN -e 'install Date::Manip'
	perl -MCPAN -e 'install Math::Complex'
	perl -MCPAN -e 'install LWP::Simple'
	perl -MCPAN -e 'install Class::Inspector'
	perl -MCPAN -e 'install Tie::DataDumper'
	perl -MCPAN -e 'install Tie::SaveLater'
	perl -MCPAN -e 'install Statistics::Distributions'
	perl -MCPAN -e 'install File::Touch'
	perl -MCPAN -e 'install Unicode::String'
	perl -MCPAN -e 'install Graphics::GnuplotIF'
	perl -MCPAN -e 'install Protocol::Modbus'
	perl -MCPAN -e 'install String::Random'
	perl -MCPAN -e 'install Crypt::Eksblowfish::Bcrypt'
	yum -y install openssl-devel
	yum -y install mod_ssl
	perl -MCPAN -e 'install Crypt::OpenSSL::Random'
	perl -MCPAN -e 'install Crypt::OpenSSL::RSA'
	perl -MCPAN -e 'install Crypt::OpenSSL::AES'
	perl -MCPAN -e 'install Crypt::CBC'


install: CPAN /var/lock/SemaforeFile/ $(html)/Celltest.ico $(html)/celltest/png/ $(cgi)/celltest/ $(cgi)/front/ $(html)/tmp/ /home/celltest/conf/ /usr/local/bin/celltest/user_exec/ /usr/local/bin/celltest/logprograms/ libs RFClibs devs lock $(html)/index.html start_servers /usr/local/bin/awk/ /home/celltest/infofiles/ /usr/local/bin/history-plot /home/celltest/info_table.txt
	@for i in $(SUBDIRS); do \
		echo "Installing in $$i..."; \
		(cd $$i; $(MAKE) $(MFLAGS) $(MYMAKEFLAGS) install); \
	done
	cp -R cgi/*.cgi $(cgi)/celltest/
	cp -R html/* $(html)/celltest/
	cp -R bin/* /usr/local/bin/celltest/
	cp -R sbin/* /usr/local/bin/
	cp -R home/* /home/celltest/
	cp -R logprograms/* /usr/local/bin/celltest/logprograms/
	chown -R $(user):$(group) /home/celltest/
	chmod 775 /home/celltest
	cp build /home/celltest/
	cp update_host.txt /home/celltest/
	./install_AFMpm.bash
	for file in $(BINFILES); do \
		rm -f /usr/local/bin/$$file; \
		ln -s /usr/local/bin/celltest/$$file /usr/local/bin/$$file; \
	done
	chmod 775 /home/celltest/conf/
	chmod 666 /home/celltest/conf/conf.lock
	/usr/sbin/usermod -a -G lock sofc
	./fix_ssl.bash
	@echo "Remember to append this line to /etc/rc.local: '/usr/local/bin/celltest/start_servers &'"
	@echo ""
	@echo "It is advisable to enable automatic software updates by running"
	@echo "/usr/local/bin/celltest/celltest_updater.pl once a week (as root)"
	@echo "To do so automatically, add the following line to root's crontab file (refer man crontab):"
	@echo "0 8 * * 1 /usr/local/bin/celltest/celltest_updater.pl >> /root/update_log.txt &"
	@echo "This will try to update the program on mondays at 8 AM."
	@echo ""
	@echo "Also remember to add all rig users to group $(group)!"
	@echo ""
	@echo "Also remember to run: 'make patch' from the install folder to enable full size Modbus reading of up to 256 byte in one packed "
	@echo ""
	@echo "If this installation is to be run as a stand allone server installation, refer the manual as to how to setup the password server"
	@echo "If the server is to be part of a cluster, make sure that RFCcontrol-ssl-server is started at bootup"
	@echo "To ensure this, at the following line to /etc/rc.local"
	@echo "/usr/local/bin/celltest/RFCcontrol-ssl-server > /dev/null &"
	@echo ""
	@echo "This can be setup automatically by running 'make SSL-server'"
	@echo ""

SSL-server:
	bash setup_ssl.bash


update: CPAN test update_common


update_force: CPAN update_common
	for file in $(BINFILES); do \
		rm -f /usr/local/bin/$$file; \
		ln -s /usr/local/bin/celltest/$$file /usr/local/bin/$$file; \
	done

/usr/local/bin/history-plot:
	ln -s /usr/local/bin/celltest/history-plot-3.0.pl /usr/local/bin/history-plot

/usr/local/bin/celltest/awk: /usr/local/bin/celltest/
	mkdir /usr/local/bin/celltest/awk/

/usr/local/bin/awk: /usr/local/bin/celltest/awk/
	ln -s /usr/local/bin/celltest/awk /usr/local/bin/awk

update_common: /var/lock/SemaforeFile/ $(html)/Celltest.ico $(html)/celltest/png/ $(cgi)/celltest/ $(cgi)/front/ $(html)/tmp/ /home/celltest/ /usr/local/bin/celltest/user_exec/ /usr/local/bin/celltest/logprograms/ libs RFClibs devs lock $(html)index.html start_servers /usr/local/bin/awk/ /home/celltest/infofiles/ /usr/local/bin/history-plot /home/celltest/info_table.txt
	for file in $(BINFILES); do \
		rm -f /usr/local/bin/$$file; \
	done	
	@for i in $(SUBDIRS); do \
		echo "Installing in $$i..."; \
		(cd $$i; $(MAKE) $(MFLAGS) $(MYMAKEFLAGS) update); \
	done
	cp -R cgi/*.cgi $(cgi)/celltest/
	cp -R html/* $(html)/celltest/
	cp -R bin/* /usr/local/bin/celltest/
	cp -R sbin/* /usr/local/bin/
	cp -R logprograms/* /usr/local/bin/celltest/logprograms/
	./install_AFMpm.bash
	for file in $(BINFILES); do \
		rm -f /usr/local/bin/$$file; \
		ln -s /usr/local/bin/celltest/$$file /usr/local/bin/$$file; \
	done
	chown -R $(user):$(group) /home/celltest/
	chmod 775 /home/celltest
	cp build /home/celltest/
	cp home/conf/UI.cfg /home/celltest/conf/
	cp home/conf/configfile.stub /home/celltest/conf/
	cp update_host.txt /home/celltest/
	./set_start_CGI.pl
	chown $(user):$(group) $(html)/tmp/ 
	chmod 775 $(html)/tmp/
	chmod 666 /home/celltest/*.lock
	chmod 640 /home/celltest/secret.key
	chmod 700 /usr/local/bin/celltest/start_servers
	chown $(user):$(group) /home/celltest/infofiles
	chmod 775 /home/celltest/infofiles
	chmod 775 /home/celltest/conf/
	chmod 666 /home/celltest/conf/conf.lock
	./set_lock_users.bash	
	chgrp lock /var/lock/SemaforeFile
	chmod 775 /var/lock/SemaforeFile
	bash setup_ssl.bash
	killall report-server || true
	sleep 1
	/usr/local/bin/celltest/start_servers > /dev/null
	./fix_ssl.bash

start_servers: /usr/local/bin/celltest/ /usr/local/bin/celltest/start_servers

/usr/local/bin/celltest/start_servers:
	@echo "Creating start_servers file for automatic server start"
	@echo "/usr/local/bin/celltest/serial-socket-server-9.0.pl ttyS0 9600 >> /home/celltest/ttyS0_log.txt 2>> /home/celltest/ttyS0_error.txt &" > start_servers
	@echo "/bin/su - sofc -s /bin/sh -c 'cd /home/sofc; /usr/local/bin/celltest/report-server &'" >> start_servers
	chmod 700 start_servers
	cp start_servers /usr/local/bin/celltest/
	rm -rf start_servers

lock:
	/bin/touch /home/celltest/info.lock
	/bin/touch /home/celltest/proglog.lock
	/bin/touch /home/celltest/pwd.lock
	/bin/touch /home/celltest/error.lock
	/bin/chmod 666 /home/celltest/error.lock
	/bin/touch /home/celltest/error.txt
	/bin/chmod 666 /home/celltest/error.txt

$(html)/Celltest.ico: $(html)/celltest/
	rm -rf $(html)/Celltest.ico 
	ln -s $(html)/celltest/Celltest.ico $(html)/Celltest.ico 

$(html)/index.html:
	cp index.html $(html)/
	@echo "Copying index.html to default location!"

/home/celltest/infofiles: /home/celltest/
	mkdir /home/celltest/infofiles
	chown $(user):$(group) /home/celltest/infofiles
	chmod 775 /home/celltest/infofiles

/home/celltest/conf: /home/celltest/
	mkdir /home/celltest/conf
	chown $(user):$(group) /home/celltest/conf

/home/celltest: 
	mkdir /home/celltest
	chown $(user):$(group) /home/celltest

/home/celltest/info_table.txt: /home/celltest/
	touch /home/celltest/info_table.txt
	chown $(user):$(group) /home/celltest/info_table.txt
	chmod 664 /home/celltest/info_table.txt

$(cgi)/celltest:
	mkdir $(cgi)/celltest

$(cgi)/front:
	mkdir $(cgi)/front

$(html)/celltest:
	mkdir $(html)/celltest

$(html)/celltest/png: $(html)/celltest/
	mkdir $(html)/celltest/png
	chmod 777 $(html)/celltest/png

$(html)/tmp:
	mkdir $(html)/tmp/
	chown $(user):$(group) $(html)/tmp/ 
	chmod 775 $(html)/tmp/

/usr/local/bin/celltest:
	mkdir /usr/local/bin/celltest

/usr/local/bin/celltest/user_exec: /usr/local/bin/celltest/
	mkdir /usr/local/bin/celltest/user_exec

/usr/local/bin/celltest/logprograms: /usr/local/bin/celltest/
	mkdir /usr/local/bin/celltest/logprograms

libs:
	for file in $(LIBS); do \
		cp $$file $(libdir)/; \
	done

RFClibs: $(libdir)/RFC/
	for file in $(RFC); do \
		cp RFC/$$file $(libdir)/RFC/; \
	done

$(libdir)/RFC:
	mkdir $(libdir)/RFC/

devs:
	for file in $(DEVS); do \
		cp $$file $(libdir)/; \
	done

# Note that uninstall does not remove /home/celltest or the generated data files #

uninstall:
	rm -rf /usr/local/bin/celltest
	rm -rf $(cgi)/celltest
	rm -rf $(html)/celltest
	rm -rf /usr/local/bin/history-plot
	if test !-d /usr/local/bin/elchemea/; \
		then if test !-d /usr/local/bin/analytic/; \
			for file in $(LIBS); do \
			rm $(libdir)/$$file; \
			done \
		fi \
	fi
	for file in $(DEVS); do \
		rm $(libdir)/$$file; \
	done
	for file in $(RFC); do \
		rm $(libdir)/RFC/$$file; \
	done
	rmdir $(libdir)/RFC/
	@echo "AFM.pm was not removed, if this lib is to be removed, do so manually!"
	@echo "User generated files and configurations are maintained in /home/http/html"
	@echo "as well as in the respective user home directories"
	@echo "Delete these directories manually if those files are to be removed as well!"

## Only used by software distributor ##
dist: clean
	@echo "Retrieving latest committed files . . . ."
	co *.pm
	co RFC/*.pm
	for file in `ls --hide=RCS --hide=awk bin`; do \
		co bin/$$file; \
	done
	for file in `ls --hide=RCS sbin`; do \
		co sbin/$$file; \
	done
	for file in `ls --hide=RCS dbload`; do \
		co dbload/$$file; \
	done
	co cgi/*.cgi
	co html/*.css
	co html/*.js
	co html/*.html
	co sbin/*.py
	@echo "Compiling manual";
	(cd manual; $(MAKE) $(MFLAGS) $(MYMAKEFLAGS) all)
	cp manual/manual.pdf html/manual.pdf
	@echo "Incrementing build number";
	../incr_build_nr.pl
	@cat build
	cp build /home/celltest/
	cp /home/celltest/conf/UI.cfg home/conf/
	@echo "Building distribution tar file . . ."
	tar --exclude=RCS --exclude=manual -czf ../RFCcontrol-$(dist_version).tgz ../RFCcontrol
	cp ../RFCcontrol-$(dist_version).tgz /home/http/html/dist/
	rm -rf /home/http/html/dist/RFCcontrol-$(dist_version)-unstable.tgz

## Only used by software distributor ##
publish:
	md5sum ../RFCcontrol-$(dist_version).tgz > ../RFCcontrol_md5.txt
	sed -i 's/\.\.\///' ../RFCcontrol_md5.txt
	scp ../RFCcontrol-$(dist_version).tgz sofc@www.elchemea.dk:/var/www/html/dist/
	scp ../RFCcontrol_md5.txt sofc@www.elchemea.dk:/var/www/html/dist/
	scp /home/http/html/dist/RFCcontrol_version.txt sofc@www.elchemea.dk:/var/www/html/dist/
	scp manual/manual.pdf sofc@www.elchemea.dk:/var/www/html/RFCcontrol/

## Only used by software distributor ##
test_dist: clean
	@echo "Retrieving latest committed files for test distribution . . . ."
	co *.pm
	co RFC/*.pm
	for file in `ls --hide=RCS --hide=awk bin`; do \
		co bin/$$file; \
	done
	for file in `ls --hide=RCS sbin`; do \
		co sbin/$$file; \
	done
	for file in `ls --hide=RCS dbload`; do \
		co dbload/$$file; \
	done
	co cgi/*.cgi
	co html/*.css
	co html/*.js
	co html/*.html
	co sbin/*.py
	cp /home/celltest/conf/UI.cfg home/conf/
	(cd manual; $(MAKE) $(MFLAGS) $(MYMAKEFLAGS) all)
	cp manual/manual.pdf html/manual.pdf
	@echo "Building distribution tar file . . ."
	tar --exclude=RCS --exclude=manual -czf ../RFCcontrol-$(dist_version)-unstable.tgz ../RFCcontrol
	cp ../RFCcontrol-$(dist_version)-unstable.tgz /home/http/html/dist/

clean:
	rm -rf test.t
	rm -rf start_servers
	rm -ff INSTALL_RIG
	@for i in $(SUBDIRS); do \
		echo "Clearing in $$i..."; \
		(cd $$i; $(MAKE) $(MFLAGS) $(MYMAKEFLAGS) clean); \
	done

test: CPAN /var/lock/SemaforeFile/
	@echo "Current version to be installed:"
	@echo "RFCcontrol-$(version)"
	@echo "Current build to be installed:"
	@cat build
	@echo "Testing configurations for all rigs with new versin/build. . . ."
	./make_test.pl
	perl test.t

patch:
	@echo "patching cpan Protocol::Modbus version 0.09 file: $(path_TCP_pm)"
	patch $(path_TCP_pm) < ModbusTCP.pm.patch

p2c:
	rpm -ivh p2c/*.rpm


install_all: p2c CPAN all test install


/var/lock/SemaforeFile/:
	mkdir /var/lock/SemaforeFile
	chmod 775 /var/lock/SemaforeFile
	chgrp lock /var/lock/SemaforeFile


