summaryrefslogblamecommitdiffstats
path: root/satellit_upgrader/updater.template.sh
blob: d58d85029a05681d1514e6509937d16684f2dd1f (plain) (tree)
1
2
3
4
5
6
7
8




                                                                                             

                                                                          
                                              


              






                                                                        


                                                                          




                                                                          
 


                          
              
          

                                                           
                                                     

             
                      



                                        

                                                        

                        

                                                
                                                                   



                                                 




                                                  













                                                                                                      

                                                                        












                                                                                               

 

                                                         
                                         


                                               
                                 
                                   
                                   
                                             
                                               
 

                                                      
                                                     


                                               
                                         
                                   

                                                                 
 

                                                                               
                                                                                     







                                                                   
                               
                                                                                       




                                                                                       
                                                                                                                                                       

                                                      





                                                                                                                     
          
  
 








                                                                                    





                                                                                                           
                                                            
                               
             



                                                                                    
                                   
 

                                                            
















                                                                                                                                       






                                                                                                                             
                                                            
         












                                                                                                                                                                             
                                                                                                                      
           
                   

  



                                                                                      
                      


                                                                                                                                     
                                                                                     


                                                  
                                                                                                                           
                                                    

                                                      
                                                






















                                                                                                                                                         
                                     
          

                                                      
                                                       



                                                                                    
                                                     

                                                                      



                                                                             
                                                 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        




                                                                                                                                
                                   







                                                                            

                                                                             


                                                                              





                                                                                                                                                             
 
                                           

                                                       

                                                                
                                                                           





                                                                                                                                                                               
                                                                                                                       
                                        
                                                          
 
                                                


                                                                                                                                                                                                                                                         
                                             

  
                                                            

                                                                                  
                                               




                                                                                                                                                 

                                                                                                         




                                                                                               
                                           

                                 
                                    
  
 



                                                                             
                         
                                                                                                  

                                                                                                           
                                                     




                                                                                                                                                                             

                             
               
                                                            
                                                                                
                                      
                                                                                                                           
                         
  
 

                                                                               
                                              

                                                                                                                                          



                                                                                     
                                                    

                                                                                                                                                            

  
                                                            
                                                     
                                                                  
                                                                                                                              
                                                                                                      


                                                                                                       
                                                    

                                                                                                                         


                                               
          

  







                                                                            
                                                            
 
                                            

                                                                    




                                                                                                                                                          


                                                              

                                                                                                                                              
            
                                                                                                                      



                         



















                                                                                                                                          

                                                         
                         


                                                                             
                                                        
 
                                   


                                                                      
                                                                
                                                                                      
                                  
            
                                                                      

          
                                
                                                                                                                                          
                         

  
                                                          


                                                                                







                                                                                                
                                
          



                                      
                                            
                                                                                                                           

                                     
                                                          
                                                                                                                   

                                  
                                                       
                                                                                                               

  




                                                                                                               
                                                          
                                               
                                                     

                                                                                            




                                                                                         




















                                                                                                                                                                   
                                                           
                                       
                                 
                                                                                                                   
                                    



                                                               
                                    




                                                                                                      
                                






                                                                                                       

                                             
                                                   

          
 




                                                                                                                                              

  
                                           
                    
                                                                                                         



                                                                           
                   

                






                                                               
















                                                                           
              
 



                                                               
      
          
 
#!/bin/bash

# Use special param to make sure we're running under bash (in case user does "sh install.sh")
[ "x$1" != "x--exec-self" ] && exec /bin/bash "$0" --exec-self "$@"

if [ ! -d "/opt/dmsd" ] && [ ! -d "/srv/openslx/www/slx-admin" ]; then
	echo "This system doesn't look like a bwLehrpool Satellite Server"
	echo "(Or this updater is really old)"
	exit 1
fi

if [ "$(lsb_release -si)" != "Debian" ]; then
	echo "This updater only supports Debian-based satellite servers"
	exit 1
fi

TEST2=$(lsb_release -sr)
if [ "${TEST2%%.*}" -lt 8 ]; then
	echo "This Version of the bwLehrpool Satellite Server is too old!"
	exit 1
fi
if [ "${TEST2%%.*}" -gt 8 ]; then
	echo "This Version of the bwLehrpool Satellite Server is too new!"
	exit 1
fi
unset TEST2

unset TMPDIR
[ -n "$TMPDIR" ] && exit 1

IGNORE_ERRORS=
DO_UPDATE=
while [ $# -gt 0 ]; do
	[ "x$1" = "x--ignore-errors" ] && IGNORE_ERRORS=jup
	[ "x$1" = "x--update" ] && DO_UPDATE=pwarning
	shift
done
readonly IGNORE_ERRORS

declare -rg SELFPID=$$
perror () {
	if [ -n "$IGNORE_ERRORS" ]; then
		echo -n -e '\033[01;31m[ERROR]\033[00m '
		echo "$@"
		return 0
	fi
	echo -n -e '\033[01;31m[FATAL]\033[00m '
	echo "$@"
	[ -n "$TMPDIR" ] && [ -d "$TMPDIR" ] && rm -rf -- "$TMPDIR"
	[ "$$" != "$SELFPID" ] && kill "$SELFPID"
	exit 1
}

pwarning () {
	echo -n -e '\033[01;33m[WARNING]\033[00m '
	echo "$@"
}

if [ "$UID" != "0" ]; then
	perror "Must be running as root"
fi

# ** Extract value from text file containing key=value pairs
extractfield () {
	grep -m1 "^\s*$2\b" "$1" | awk -F '=' '{print $2}' | sed 's/\s//g'
}

# ** Wrap mysql command line client so we're always using the deb-sys-maint credentials
mysql () {
	"$(which mysql)" --defaults-extra-file=/etc/mysql/debian.cnf --default-character-set=utf8 "$@"
}

# ** Restart given systemd service, warn if it fails but do not bail out
restart_service () {
	if ! systemctl restart "$1"; then
		pwarning "Could not restart service $1 - !! YOU SHOULD REBOOT THE SERVER !!"
		systemctl status "$1"
	fi
}

# ** Recursively set permissions of given directory to 0755/0644 optionally setting owner/group
fixperms () {
	[ -e "$1" ] || perror "normalize_perms: $1 does not exist"
	chmod -R a-rw,u+rwX,go+rX "$1"
	if [ -n "$2" ]; then
		chown -R "$2" "$1" || pwarning "Could not change owner of $1 to $2"
	fi
}

# ** Constants - to be patched by the packaging script
declare -rg TARGET_WEBIF_VERSION="%TARGET_WEBIF_VERSION%"
declare -rg TGZ_SLXADMIN="%TGZ_SLXADMIN%"
declare -rg TGZ_DOZMOD="%TGZ_DOZMOD%"
declare -rg TGZ_TASKMANAGER="%TGZ_TASKMANAGER%"
declare -rg TGZ_TFTP="%TGZ_TFTP%"
declare -rg TGZ_IPXE="%TGZ_IPXE%"
declare -rg TGZ_LDADP="%TGZ_LDADP%"
declare -rg TGZ_DNBD3="%TGZ_DNBD3%"
declare -rg PAYLOAD_OFFSET="%PAYLOAD_OFFSET%"
declare -rg SLXADMIN_FOOTER="%SLXADMIN_FOOTER%"

# ** Constants - hardcoded or determined at runtime
declare -rg PATH_SLXADMIN="/srv/openslx/www/slx-admin"
declare -rg PATH_SLXADMINCACHE="/var/cache/slx-admin"
declare -rg PATH_DOZMOD="/opt/dmsd"
declare -rg PATH_TASKMANAGER="/opt/taskmanager"
declare -rg PATH_TFTP="/srv/openslx/tftp"
declare -rg PATH_IPXE="/opt/openslx/ipxe"
declare -rg PATH_LDADP="/opt/ldadp"
declare -rg PATH_DNBD3="/opt/openslx/dnbd3"
declare -rg PACKAGE_LIBJANSSON="libjansson4"	# needed by dnbd3

# ** Check if constants have been filled, bail out otherwise
if [ -z "$TARGET_WEBIF_VERSION" ] || [[ "$TARGET_WEBIF_VERSION" == %*% ]]; then
	[ -n "$TGZ_SLXADMIN" ] && perror "Bad upgrader: TARGET_WEBIF_VERSION not set"
fi
if [ -z "$PAYLOAD_OFFSET" ] || [[ "$PAYLOAD_OFFSET" == %*% ]]; then
	perror "Bad upgrader: PAYLOAD_OFFSET not set"
fi

# **********************************************************

# Get current webif version
if [ -n "$TGZ_SLXADMIN" ]; then
	declare -rg CURRENT_WEBIF_VERSION=$(cat "${PATH_SLXADMIN}/version" | tail -n 1)
	echo "bwLehrpool Satellite Server Update"
	echo -n "Currently installed version: "
	sed -r 's/([0-9]{4})([0-9]{3})([0-9]{2})/\1-\2-\3/' <<<"$CURRENT_WEBIF_VERSION"
	echo -n "This update package:         "
	sed -r 's/([0-9]{4})([0-9]{3})([0-9]{2})/\1-\2-\3/' <<<"$TARGET_WEBIF_VERSION"
	if [ -z "$CURRENT_WEBIF_VERSION" ] || [ "$TARGET_WEBIF_VERSION" = "missing" ] || [ "$CURRENT_WEBIF_VERSION" -le "$TARGET_WEBIF_VERSION" ]; then
		: # Negate so NaN triggers else branch
	else
		${DO_UPDATE:-perror} "This update seems to be older than the server version you're currently running"
	fi
	if [ -z "$DO_UPDATE" ]; then
		echo "If you want to install this upate, run again with --update parameter:"
		echo "eg. sh $0 --update"
		exit 0
	fi
fi

# **** Start generating dhparam early as it takes a long time **********************
declare -rg DHPARAM="/etc/lighttpd/dhparam.pem"
DH_PID=
if ! [ -s "$DHPARAM" ]; then
	openssl dhparam -out "$DHPARAM" 2048 >/dev/null 2>&1 &
	DH_PID=$!
fi


# **************** Fix tmpdelete cronjob *******************
if [ -f "/etc/cron.daily/tmpdelete.sh" ]; then
	[ -f "/etc/cron.daily/tmpdelete" ] || mv "/etc/cron.daily/tmpdelete.sh" "/etc/cron.daily/tmpdelete"
	rm -f -- "/etc/cron.daily/tmpdelete.sh"
fi

# ************** Extract payload ***************************
declare -rg TMPDIR=$(mktemp -d)
export TMPDIR
[ -z "$TMPDIR" ] && perror "Could not create temporary directory for installer"
dd "bs=$PAYLOAD_OFFSET" "if=$0" skip=1 | tar -z -x -C "$TMPDIR"
RET=$?
[ "$RET" -ne 0 ] && perror "Extracting installer payload failed with exit code $RET"
declare -rg FILEDIR="$TMPDIR/files"

# **********************************************************

# ********************** Taskmanager ***********************
# Do this first in case one of the later updates depends on the taskmanager
if [ -n "$TGZ_TASKMANAGER" ]; then
	[ -e "$TMPDIR/$TGZ_TASKMANAGER" ] || perror "$TGZ_TASKMANAGER missing from payload"
	echo "* Task manager"
	echo "Extracting new jar and data"
	# Replacement trick (see slxadmin)
	tar -x -C "$PATH_TASKMANAGER" -f "$TMPDIR/$TGZ_TASKMANAGER" || perror "Could not extract $TGZ_TASKMANAGER to $PATH_TASKMANAGER"
	rm -rf -- "$PATH_TASKMANAGER/data" "$PATH_TASKMANAGER/scripts" "$PATH_TASKMANAGER/plugins" "$PATH_TASKMANAGER/taskmanager.sh"
	tar -x -C "$PATH_TASKMANAGER" -f "$TMPDIR/$TGZ_TASKMANAGER"
	fixperms "$PATH_TASKMANAGER" root:root
	chmod -R a+x "$PATH_TASKMANAGER/scripts"
	echo "Restarting service"
	restart_service taskmanager
	echo "Taskmanager upgrade complete"
fi

# *****************taskmanager sudo config *****************
if [ -s "$FILEDIR/tm-sudo-config" ]; then
	echo "Installing new sudo config for taskmanager"
	cp -f "$FILEDIR/tm-sudo-config" "/etc/sudoers.d/taskmanager" || pwarning "Could not update sudo conf for taskmanager"
	chmod 0440 "/etc/sudoers.d/taskmanager"
fi

# ************************** IPXE **************************
IPXE_PID=
if [ -n "$TGZ_IPXE" ]; then
	[ -e "$TMPDIR/$TGZ_IPXE" ] || perror "$TGZ_IPXE missing from payload"
	echo "* iPXE source code"
	echo "Extracting"
	rm -rf -- "$PATH_IPXE"
	mkdir -p "$PATH_IPXE"
	tar -x -C "$PATH_IPXE" -f "$TMPDIR/$TGZ_IPXE" || perror "Could not extract $TGZ_IPXE to $PATH_IPXE"
	fixperms "$PATH_IPXE" taskmanager:taskmanager
	echo "Resetting pxe menu"
	mysql -e 'UPDATE openslx.property SET value = "invalid" WHERE name = "server-ip"' || pwarning "Could not reset pxe menu status; manual regeneration of menu required"
	echo "iPXE upgrade complete"
	# Trigger default compile in the background so the next regen doesn't take too long
	{
		cd "$PATH_IPXE/src" && sudo -n -u taskmanager nice -n 10 make -j2 bin/undionly.kkkpxe > /dev/null 2>&1
	} &
	IPXE_PID=$!
fi

# ************************** SLX-Admin *********************
if [ -n "$TGZ_SLXADMIN" ]; then
	[ -e "$TMPDIR/$TGZ_SLXADMIN" ] || perror "$TGZ_SLXADMIN missing from payload."
	echo "* SLX-Admin: $CURRENT_WEBIF_VERSION -> $TARGET_WEBIF_VERSION"
	# Test archive
	INCMODS=$(mktemp)
	tar tf "$TMPDIR/$TGZ_SLXADMIN"  | grep -oP '^modules-available/[^/]+/$' > "$INCMODS" || perror "Could not read $TGZ_SLXADMIN"
	# Remove old files - wipe selectively, just in case someone added a new module by hand
	rm -rf -- "$PATH_SLXADMIN/"{inc,apis,modules,templates,Mustache,script,style}
	while read -r line || [[ -n "$line" ]]; do
		rm -rf -- "$PATH_SLXADMIN/$line"
	done < "$INCMODS"
	tar -x -C "$PATH_SLXADMIN" -f "$TMPDIR/$TGZ_SLXADMIN" || perror "Could not extract $TGZ_SLXADMIN to $PATH_SLXADMIN"
	rm -f -- "$PATH_SLXADMIN/config.php.example"
	# New config.php supplied
	if [ -s "$FILEDIR/slxadmin-config.php" ]; then
		echo "Updating slx-admin config"
		# Get data from old config
		OLDFOOTER="$(grep -m 1 CONFIG_FOOTER "${PATH_SLXADMIN}/config.php"  | awk -F "'" '{print $4}' | sed 's/[ \[\]\(\)]*Update.*$//;s/#/+/g')"
		SQLPASS=$(grep -m1 '^define.*CONFIG_SQL_PASS.*;' "${PATH_SLXADMIN}/config.php" | awk -F "'" '{print $4}')
		# Patch config with new features using old mysql password
		if [ -z "$SQLPASS" ]; then
			pwarning "Could not extract old slx-admin mysql password - cannot update config :("
		else
			sed "s/%MYSQL_OPENSLX_PASS%/${SQLPASS}/g" "$FILEDIR/slxadmin-config.php" > "${PATH_SLXADMIN}/config.php"
		fi
		# Update version info in footer
		[ -z "$OLDFOOTER" ] && OLDFOOTER="Unknown base version"
		FOOTER="$SLXADMIN_FOOTER"
		[[ "$FOOTER" == %*% ]] && FOOTER=
		if [ -z "$FOOTER" ]; then
			D=$(stat -c %Y "$0")
			[ -z "$D" ] && D=$(date +%s)
			D=$(date -d "@$D" "+%y-%m-%d %H:%M")
			FOOTER="Unknown $D"
		fi
		FOOTER="$OLDFOOTER [Update: ${FOOTER}]"
		sed -i "s#^.*define.*CONFIG_FOOTER.*\$#define('CONFIG_FOOTER', '${FOOTER}');#" "${PATH_SLXADMIN}/config.php"
		grep -q 'CONFIG_FOOTER' "${PATH_SLXADMIN}/config.php" || echo "define('CONFIG_FOOTER', '${FOOTER}');" >> "${PATH_SLXADMIN}/config.php"
		echo "$TARGET_WEBIF_VERSION" > "${PATH_SLXADMIN}/version"
		echo "Config updated"
	fi
	# New cronscript supplied
	if [ -s "$FILEDIR/slxadmin-cronscript" ]; then
		echo "Installing slx-admin cron script"
		cp "$FILEDIR/slxadmin-cronscript" "/opt/openslx/slxadmin-cronscript"
	fi
	# New crontab supplied
	if [ -s "$FILEDIR/slxadmin-crontab" ]; then
		echo "Installing slx-admin cron file"
		cp "$FILEDIR/slxadmin-crontab" "/etc/cron.d/slx-admin"
	fi
	# Enable modules
	(
		mkdir -p "$PATH_SLXADMIN/modules"
		cd "$PATH_SLXADMIN/modules" || perror "Cannot cd to slxadmin"
		echo "Enabling slx-admin modules"
		for mod in adduser backup baseconfig baseconfig_bwidm baseconfig_bwlp bootstrap_datepicker bootstrap_dialog bootstrap_multiselect bootstrap_switch bootstrap_timepicker dnbd3 dozmod eventlog exams js_chart js_circles js_jqueryui js_moment js_selectize js_stupidtable js_vis js_weekcalendar locationinfo locations main minilinux news rebootcontrol roomplanner runmode serversetup-bwlp session statistics statistics_reporting summernote sysconfig syslog systemstatus vmstore webinterface; do
			name=${mod%%-*}
			rm -f -- "$name"
			ln -s "../modules-available/$mod" "$name" || pwarning "Could not activate module '$mod' (alias '$name')"
		done
		# Update DB
		cd "$PATH_SLXADMIN"
		if ! ./install-all > "$TMPDIR/wwwup.log"; then
			cat "$TMPDIR/wwwup.log"
			perror "Updating the web interface database failed"
		fi
		if grep -q 'Result: UPDATE_FAILED' "$TMPDIR/wwwup.log"; then
			cat "$TMPDIR/wwwup.log"
			perror "Updating the web interface database failed"
		fi
		if [ "x$(tail -n -1 "$TMPDIR/wwwup.log")" != "xDone." ]; then
			cat "$TMPDIR/wwwup.log"
			pwarning "slxadmin updater didn't finish with 'Done.'"
		fi
	)
	# Delete old statistics api & unneeded dirs
	rm -rf -- "${PATH_SLXADMIN}/apis/statistics.inc.php" "${PATH_SLXADMIN}/doc" "${PATH_SLXADMIN}/.idea" "${PATH_SLXADMIN}/tools" "${PATH_SLXADMIN}/.git"
	# Since 90% is missing by now...
	rm -rf -- "${PATH_SLXADMIN}/lang/pt"
	# Remove link to translation util
	sed -i '/<a.*lang_translations/d' "${PATH_SLXADMIN}/modules-available/main/templates/main-menu.html"

	fixperms "$PATH_SLXADMIN" root:root
	chmod 0640 "$PATH_SLXADMIN/config.php"
	chown root:www-data "$PATH_SLXADMIN/config.php"
	# config.tgz symlink -> db entry
	if [ -L /srv/openslx/www/boot/default/config.tgz ]; then
		echo "Migrating config activation from symlink to database"
		CONFTGZ=$(readlink /srv/openslx/www/boot/default/config.tgz | sed "s/'/\\\'/g")
		echo "config.tgz links to '$CONFTGZ'"
		mysql -e "INSERT IGNORE INTO openslx.configtgz_location (locationid, configid) SELECT 0, configid FROM openslx.configtgz WHERE filepath = '$CONFTGZ' LIMIT 1" \
			|| pwarning "Could not convert default config.tgz setting - do so manually"
		rm -f -- /srv/openslx/www/boot/default/config.tgz
	fi
	ln -s -f "$PATH_TFTP" "/srv/openslx/www/tftp" || perror "Could not symlink $PATH_TFTP to /srv/openslx/www/tftp"
	mkdir -p "${PATH_SLXADMINCACHE}"
	fixperms "${PATH_SLXADMINCACHE}" www-data:www-data

	echo "Symlinking bwIDM slx-admin config"
	rm -f -- "/srv/openslx/www/slx-admin/modules-available/baseconfig_bwidm/baseconfig/settings.json"
	ln -s "${PATH_SLXADMINCACHE}/baseconfig-bwidm_settings.json" /srv/openslx/www/slx-admin/modules-available/baseconfig_bwidm/baseconfig/settings.json || \
		pwarning "Could not set link ${PATH_SLXADMINCACHE}/baseconfig-bwidm_settings.json to /srv/openslx/www/slx-admin/modules-available/baseconfig_bwidm/baseconfig/settings.json - do so manually if you need bwIDM login on client computers"
	echo "Web interface upgrade complete"
fi

# ************************* Dozmod *************************
if [ -n "$TGZ_DOZMOD" ]; then
	[ -e "$TMPDIR/$TGZ_DOZMOD" ] || perror "$TGZ_DOZMOD missing from payload."
	echo "* bwLehrpool-Suite Server (dmsd)"
	echo "Adjusting mysql permissions of user sat"
	mysql -e 'GRANT CREATE, ALTER ON sat.* TO sat@localhost' || perror "Could not GRANT permissions ON sat.* to sat@localhost"
	mysql -e 'GRANT SELECT ON openslx.location TO sat@localhost' || perror "Could not GRANT permissions ON openslx.location to sat@localhost"
	echo "Extracting new jar"
	tar -x -C "$PATH_DOZMOD" -f "$TMPDIR/$TGZ_DOZMOD" || perror "Could not extract $TGZ_DOZMOD to $PATH_DOZMOD"
	rm -rf -- "$PATH_DOZMOD/bwLehrpoolSuite_Server.jar" "$PATH_DOZMOD/control.sh" "$PATH_DOZMOD/flag"
	tar -x -C "$PATH_DOZMOD" -f "$TMPDIR/$TGZ_DOZMOD"
	if mysql -e 'SHOW TABLES' openslx | grep -q '^location$'; then
		echo "Enabling location feature"
		sed -i '/^db.location-table\b/d' "$PATH_DOZMOD/config.properties"
		echo 'db.location-table = openslx.location' >> "$PATH_DOZMOD/config.properties"
	fi
	fixperms "$PATH_DOZMOD" root:images
	echo "Restarting service"
	restart_service dmsd
	echo "dmsd upgrade complete"
fi

# ************************** TFTP **************************
if [ -n "$TGZ_TFTP" ]; then
	[ -e "$TMPDIR/$TGZ_TFTP" ] || perror "$TGZ_TFTP missing from payload"
	echo "* TFTP"
	echo "Extracting"
	rm -rf -- "$PATH_TFTP/v4" "$PATH_TFTP/v6" "$PATH_TFTP/ipxelinux.0" "$PATH_TFTP/pxelinux.0"
	mkdir -p "$PATH_TFTP"
	tar -x -C "$PATH_TFTP" -f "$TMPDIR/$TGZ_TFTP" || perror "Could not extract $TGZ_TFTP to $PATH_TFTP"
	fixperms "$PATH_TFTP" taskmanager:taskmanager
	echo "Resetting pxe menu"
	mysql -e 'UPDATE openslx.property SET value = "invalid" WHERE name = "server-ip"' || pwarning "Could not reset pxe menu status; manual regeneration of menu required"
	echo "TFTP upgrade complete"
fi

echo "* Configuring lighttpd"

RESTART_LIGHTY=
# ********************** lighttpd config *******************
if [ -e "$FILEDIR/lighttpd.conf" ] && [ -e "/etc/lighttpd/lighttpd.conf" ]; then
	echo "Replacing lighttpd.conf"
	cp "$FILEDIR/lighttpd.conf" "/etc/lighttpd/lighttpd.conf" || perror "Could not replace /etc/lighttpd/lighttpd.conf"
	RESTART_LIGHTY=ja
fi

# ********************** lighttpd auto ssl *******************
if [ -e "$FILEDIR/lighttpd-auto-ssl.sh" ] && [ -d "/usr/share/lighttpd" ]; then
	echo "Installing lighttpd auto-ssl.sh"
	cp "$FILEDIR/lighttpd-auto-ssl.sh" "/usr/share/lighttpd/auto-ssl.sh" || perror "Could not replace /usr/share/lighttpd/auto-ssl.sh"
	RESTART_LIGHTY=ja
fi

# ********************** lighttpd-include-conf-d.sh *******************
if [ -e "$FILEDIR/lighttpd-include-conf-d.sh" ] && [ -d "/usr/share/lighttpd" ]; then
	echo "Installing lighttpd include-conf-d.sh"
	cp "$FILEDIR/lighttpd-include-conf-d.sh" "/usr/share/lighttpd/include-conf-d.sh" || perror "Could not replace /usr/share/lighttpd/include-conf-d.sh"
	RESTART_LIGHTY=ja
fi

# ********************** lighttpd php_children *************
if [ -e "$FILEDIR/patch_lighttpd_phpchildren" ]; then
	echo "Installing script to set dynamic php children value"
	cp "$FILEDIR/patch_lighttpd_phpchildren" /usr/local/sbin || perror "Could not copy patch_lighttpd_phpchildren script!"
	chmod +x /usr/local/sbin/patch_lighttpd_phpchildren     # Just to sleep better in dark nights.
	if [ -f "/lib/systemd/system/lighttpd.service" ]; then
		# service file found, patching dynamic php children value at system start via patchfile
		if ! grep -q patch_lighttpd_phpchildren "/lib/systemd/system/lighttpd.service"; then
			echo "Patching service file"
			sed -i 's#\[Service\]#\[Service\]\nExecStartPre=\-/usr/local/sbin/patch_lighttpd_phpchildren#g' \
				/lib/systemd/system/lighttpd.service || perror "Could not patch service file!"
			systemctl daemon-reload
			RESTART_LIGHTY=ja
		fi
	fi
fi

# ****************** lighttpd extract cert *****************
declare -rg CERT_KEY_FILE="/etc/lighttpd/server.pem"
declare -rg PUB_CERT_FILE="/etc/lighttpd/pub-cert.pem"
if [ -s "$CERT_KEY_FILE" ] && ! [ -s "$PUB_CERT_FILE" ]; then
	echo "Extracting public certificate from server.pem"
	openssl x509 -outform pem -in "$CERT_KEY_FILE" -out "$PUB_CERT_FILE"
fi

# ************************** PHP ***************************

declare -rg PHPINIFILE=/etc/php5/cgi/php.ini
if ! grep -q -E '^\s*upload_max_filesize = 100M' "$PHPINIFILE"; then
	echo "PHP: Increasing upload_max_filesize to 100MB"
	if grep -q -E '^\s*upload_max_filesize' "$PHPINIFILE"; then
		sed -i -e '/^\s*upload_max_filesize/c\upload_max_filesize = 100M' "$PHPINIFILE" || pwarning "Could not increase PHP upload limit :( (1.a)"
	else
		echo "upload_max_filesize = 100M" >> "$PHPINIFILE" || pwarning "Could not incease PHP upload limit :( (2.a)"
	fi
fi
if ! grep -q -E '^\s*post_max_size = 100M' "$PHPINIFILE"; then
	echo "PHP: Increasing post_max_size to 100MB"
	if grep -q -E '^\s*post_max_size' "$PHPINIFILE"; then
		sed -i -e '/^\s*post_max_size/c\post_max_size = 100M' "$PHPINIFILE" || pwarning "Could not increase PHP upload limit :( (1.b)"
	else
		echo "post_max_size = 100M" >> "$PHPINIFILE" || pwarning "Could not incease PHP upload limit :( (2.b)"
	fi
	RESTART_LIGHTY=ja
fi

# ********************** atftpd.service ********************
if [ -e "$FILEDIR/atftpd.service" ]; then
	echo "* Replacing atftpd.service"
	cp "$FILEDIR/atftpd.service" "/etc/systemd/system/atftpd.service" || perror "Could not replace /etc/systemd/system/atftpd.service"
	ln -s -f "../atftpd.service" "/etc/systemd/system/multi-user.target.wants/"
	systemctl daemon-reload
	restart_service atftpd
	echo "Service file replaced"
fi

# ********************** dmsd.service **********************
if [ -e "$FILEDIR/dmsd.service" ]; then
	echo "* Replacing dmsd.service"
	cp "$FILEDIR/dmsd.service" "/etc/systemd/system/dmsd.service" || perror "Could not replace /etc/systemd/system/dmsd.service"
	ln -s -f "../dmsd.service" "/etc/systemd/system/multi-user.target.wants/"
	systemctl daemon-reload
	restart_service dmsd
	echo "Service file replaced"
fi

# ********************** dnbd3 config *******************

echo "* Setting up dnbd3"

mkdir -p /etc/dnbd3-server	|| perror "Could not mkdir /etc/dnbd3-server"
mkdir -p "$PATH_DNBD3" || perror "Could not create $PATH_DNBD3"
# check for dnbd3 user: dnbd3, 10002, group dnbd3, 10002

if ! id -u dnbd3 &> /dev/null; then
	dnbd3group=$(getent group dnbd3 2>/dev/null | cut -d ":" -f 3)
	if [ -z "$dnbd3group" ]; then
		dnbd3group=10002
		echo "Creating dnbd3 group with gid $dnbd3group"
		groupadd -g "$dnbd3group" dnbd3 || perror "Could not add dnbd3 group!"
		echo "Group added"
	else
		echo "Using existing group dnbd3 with gid $dnbd3group"
	fi

	echo "Adding user dnbd3"
	useradd --no-create-home -d /nonexistent -s /bin/false --gid "$dnbd3group" --uid 10002 dnbd3 || perror "Could not add user dnbd3!"
	echo "User added"
fi

if ! dpkg -l | grep -q "^ii\\s.*$PACKAGE_LIBJANSSON"; then
	echo "Installing $PACKAGE_LIBJANSSON"
	if ! apt-get install -y "$PACKAGE_LIBJANSSON" &> "$TMPDIR/apt.log"; then
		cat "$TMPDIR/apt.log"
		pwarning "*"
		pwarning "* Warning: Could not install $PACKAGE_LIBJANSSON!"
		pwarning "*"
		pwarning "* This means the dnbd3 server will not work."
		pwarning "* Please do either \"apt-get install $PACKAGE_LIBJANSSON\" by hand or"
		pwarning "* install $PACKAGE_LIBJANSSON otherwise."
		pwarning "*"
	else
		echo "Installed"
	fi
fi

# config
if [ -e "$FILEDIR/server.conf" ]; then
	echo "Inserting server.conf (dnbd3)"
	cp "$FILEDIR/server.conf" "/etc/dnbd3-server/server.conf" || perror "Could not write /etc/dnbd3-server/server.conf"
fi
if [ -e "$FILEDIR/is-enabled" ]; then
	echo "Inserting is-enabled to $PATH_DNBD3 (dnbd3)"
	cp "$FILEDIR/is-enabled" "$PATH_DNBD3/is-enabled" || perror "Could not write /opt/openslx/dnbd3/is-enabled"
fi
if [ -e "$FILEDIR/rpc.acl" ]; then
	echo "Inserting rpc.acl to $PATH_DNBD3 (dnbd3)"
	cp "$FILEDIR/rpc.acl" "/etc/dnbd3-server/rpc.acl" || perror "Could not write /etc/dnbd3-server/rpc.acl"
fi

if [ -n "$TGZ_DNBD3" ]; then
	echo "Extracting new dnbd3-server binary"
	tar -x -C "$PATH_DNBD3" -f "$TMPDIR/$TGZ_DNBD3" || perror "Could not extract $TGZ_DNBD3 to $PATH_DNBD3"
fi

# ********************** dnbd3.service *******************
if [ -e "$FILEDIR/dnbd3-server.service" ]; then
	echo "Replacing/writing dnbd3-server.service"
	cp "$FILEDIR/dnbd3-server.service" "/etc/systemd/system/dnbd3-server.service" \
		|| perror "Could not replace/write /etc/systemd/system/dnbd3-server.service"
	ln -s -f "../dnbd3-server.service" "/etc/systemd/system/multi-user.target.wants/"
	systemctl daemon-reload
	echo "Service file replaced"
fi

# ************************** ldadp *************************
if [ -n "$TGZ_LDADP" ]; then
	[ -e "$TMPDIR/$TGZ_LDADP" ] || perror "$TGZ_LDADP missing from payload"
	echo "* LDAP/AD Proxy"
	OLD=$(md5sum "$PATH_LDADP/ldadp")
	echo "Extracting new binary"
	tar -x -C "$PATH_LDADP" -f "$TMPDIR/$TGZ_LDADP" || perror "Could not extract $TGZ_LDADP to $PATH_LDADP"
	rm -rf -- "$PATH_LDADP/logs"
	mkdir -p "$PATH_LDADP/configs" "$PATH_LDADP/pid"
	fixperms "$PATH_LDADP/configs" taskmanager:ldadp
	chmod -R o-rwx "$PATH_LDADP/configs"
	fixperms "$PATH_LDADP/pid" ldadp:root
	mkdir -p "/var/log/ldadp"
	fixperms "/var/log/ldadp" ldadp:root
	NEW=$(md5sum "$PATH_LDADP/ldadp")
	if [ "x$OLD" != "x$NEW" ]; then
		killall ldadp 2>/dev/null && pwarning "LDAP/AD Proxy was killed. Client logins might not work for a couple of minutes (see Server Status in webif)"
	fi
	echo "LDADP upgrade complete"
fi

# ************************** tmate ************************
if ! which tmate > /dev/null 2>&1; then
	echo "* Installing tmate"
	echo "deb http://ftp.debian.org/debian jessie-backports main" > /etc/apt/sources.list.d/10-added_repos.list
	echo "Running apt update..."
	if ! apt-get update > "$TMPDIR/apt.log" 2>&1; then
		cat "$TMPDIR/apt.log"
		pwarning "Adding backborts repo: update failed"
	fi
	echo "Installing package..."
	if ! apt-get install -y tmate > "$TMPDIR/apt.log" 2>&1; then
		cat "$TMPDIR/apt.log"
		pwarning "Could not install tmate. Easy remote assistance will not be available."
		pwarning "Please check whether repo 'jessie-backports' was added and install by hand."
	fi
	echo "Writing config..."
	cat > /root/.tmate.conf <<-JUSTANOTHERDOC
		set -g tmate-server-host "tmate.ruf.uni-freiburg.de"
		set -g tmate-server-port 2222
		set -g tmate-server-rsa-fingerprint   "d7:d7:06:d0:b6:0d:75:a1:ad:ec:69:18:b3:a3:c0:4a"
		set -g tmate-server-ecdsa-fingerprint "4f:c9:81:f1:1a:20:7d:6f:97:12:f2:a9:0f:f4:c5:6c"
		set -g tmate-identity ""
	JUSTANOTHERDOC

	if which tmate > /dev/null 2>&1; then
		echo "tmate installation complete!"
	fi
fi

# ******************* make sure ssh keypair exists *********
if ! [ -s /root/.ssh/id_rsa ]; then
	echo "* Generating ssh keypair"
	mkdir -p /root/.ssh
	ssh-keygen -f /root/.ssh/id_rsa -N '' -C autogenerated &>/dev/null || pwarning "Could not create new ssh keypair in /root/.ssh/id_rsa"
fi

# Wait for webif callbacks and IPXE compile
echo -n "Finishing."
sudo -u www-data -n php /srv/openslx/www/slx-admin/api.php rebootcontrol --action rebuild >/dev/null 2>&1
for i in 1 1 1 1 2 2 3 4 END; do
	CB=$(sudo -u www-data -n php /srv/openslx/www/slx-admin/api.php cb)
	[ "x$CB" != "xTrue" ] && break
	[ "$i" = "END" ] && break
	echo -n "."
	sleep $i
done
count=0
[ -n "$IPXE_PID" ] && while kill -0 "$IPXE_PID" 2>/dev/null; do
	echo -n "."
	sleep 2
	count=$(( count + 1 ))
	[ "$count" -gt 5 ] && break
done

# ************************** LIGHTY ************************
if [ -n "$RESTART_LIGHTY" ]; then
	count=0
	if [ -n "$DH_PID" ] && kill -0 "$DH_PID" 2>/dev/null; then
		echo -n ".waiting up to 5 minutes for dh param generation."
		while kill -0 "$DH_PID" 2>/dev/null; do
			echo -n "."
			sleep 2
			count=$(( count + 1 ))
			[ "$count" -gt 150 ] && break
		done
	fi

	echo -n ".restarting lighttpd."
	restart_service lighttpd
fi
echo ". done!"

echo ""
echo "Update complete. It is recommended to reboot the server."
echo ""

exit 0
# File end