#! /bin/sh
# Copyright (c) 2010, Novell Inc.
#
# Author: adrian@suse.de
#
# /etc/init.d/obsapisetup
#   and its symbolic  link
# /usr/sbin/rcobsapisetup
#
### BEGIN INIT INFO
# Provides:          obsapisetup
# Start-Before:      apache2
# Should-Start:      obsstoragesetup
# Should-Stop:       $none
# Required-Start:    mysql
# Required-Stop:     $null
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Description:       Initialize and update api database, only used in OBS Appliance
### END INIT INFO

. /etc/rc.status

# Determine the base and follow a runlevel link name.
base=${0##*/}
link=${base#*[SK][0-9][0-9]}

apidir=/srv/www/obs/api
webuidir=/srv/www/obs/webui



# make parsed output predictable 
export LC_ALL=C

. /etc/sysconfig/obs-server

if [ "$OBS_API_AUTOSETUP" != "yes" ]; then
   echo "OBS API Autosetup is not enabled in sysconfig, skipping!"
   exit 0
fi

if [ -z "$OBS_BASE_DIR" ]; then
backenddir=/srv/obs
else
backenddir="$OBS_BASE_DIR"
fi


FQHOSTNAME=`hostname -f `

if [ "$?" != "0" ]; then
  # Fallback to IP of the VM/host
  FQHOSTNAME=`ip addr | sed -n 's,.*inet \(.*\)/.* brd.*,\1,p' | grep -v ^127. | head -n 1`
  if [ "$?" != "0" -o "$FQHOSTNAME" = "" ]; then
    echo "    Can't determine hostname or IP - Network setup failed!"
    echo "    Check if networking is up and dhcp is working!"
    echo "    Using 'localhost' as FQHOSTNAME."
    FQHOSTNAME="localhost"
  fi
  USEIP=$FQHOSTNAME
fi

rc_reset
case "$1" in
	start)
                if [ ! -d /obs/MySQL ]; then
			mkdir -p /obs/MySQL
		fi

		# If we've proper hostname resolution all is fine. But if
		# there's no proper hostname resolution, adapt BSConfig.pm et al.
		### In case of the appliance, we never know where we boot up !
		OLDFQHOSTNAME="NOTHING"
		if [ -e /obs/.oldfqhostname ]; then
			OLDFQHOSTNAME=`cat /obs/.oldfqhostname`
		fi
		if [ "$FQHOSTNAME" != "$OLDFQHOSTNAME" ]; then
			echo "Appliance hostname changed from $OLDFQHOSTNAME to $FQHOSTNAME !"
			echo "Adapting hostname in BSConfig.pm"
			sed -i 's,^my.*hostname.*=.*,my \$hostname = "'"$FQHOSTNAME"'";,' \
				/usr/lib/obs/server/BSConfig.pm
			#changed IP means also that leftover jobs are invalid - cope with that
			echo "Adapting present worker jobs"
			sed -i "s,server=\"http://[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*:5352,server=\"http://$FQHOSTNAME:5352,g" \
				/$backenddir/jobs/*/* 2> /dev/null
			sed -i "s,server=\"http://[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*:5252,server=\"http://$FQHOSTNAME:5252,g" \
				/$backenddir/jobs/*/* 2> /dev/null
			#remove old workers status and idling/building markers
			rm -f /$backenddir/jobs/*/*status 2> /dev/null
			rm -f /$backenddir/workers/*/* 2> /dev/null
                        # create repo directory or apache fails when nothing got published
			mkdir -p /$backenddir/repos
			chown obsrun.obsrun /$backenddir/repos
		fi
		echo "$FQHOSTNAME" > /obs/.oldfqhostname

		echo -n "Adjust webui configuration for api"
                # it would be better to solve this in lighttpd.conf to accept also localhost:444,
                # but no idea how to solve this
                sed -i 's,^FRONTEND_HOST = .*,FRONTEND_HOST = "'"$FQHOSTNAME"'",' \
		    /srv/www/obs/webui/config/environments/production.rb
                sed -i 's,^FRONTEND_PORT = .*,FRONTEND_PORT = 444,' \
		    /srv/www/obs/webui/config/environments/production.rb
                sed -i 's,^FRONTEND_PROTOCOL = .*,FRONTEND_PROTOCOL = "'"https"'",' \
		    /srv/www/obs/webui/config/environments/production.rb
                sed -i 's,^DOWNLOAD_URL = .*,DOWNLOAD_URL = \"http://'"$FQHOSTNAME:82"'\",' \
		    /srv/www/obs/webui/config/environments/production.rb
                sed -i -e /webui_url:/d -e /webui_host:/d -e /allow_anonymous:/d \
		    /srv/www/obs/api/config/options.yml
                echo "# the following lines are always written by obsapisetup!" >> /srv/www/obs/api/config/options.yml
                echo "allow_anonymous: true" >> /srv/www/obs/api/config/options.yml
		if [ "$FQHOSTNAME" == "localhost" ] ; then
			echo "webui_host: localhost" >> /srv/www/obs/api/config/options.yml
		else
			echo "webui_host: `ip addr | sed -n 's,.*inet \(.*\)/.* brd.*,\1,p' | grep -v ^127. | head -n 1`" >> /srv/www/obs/api/config/options.yml
		fi
                echo "webui_url: https://$FQHOSTNAME:443" >> /srv/www/obs/api/config/options.yml
		echo
		OBSVERSION=`rpm -q --qf '%{VERSION}' obs-server`
		OS=`head -n 1 /etc/SuSE-release`
                RUN_INITIAL_SETUP=""
                if [ ! -e /obs/MySQL/api_production ]; then
			echo -n "Initialize MySQL databases (first time only)"
			mysqladmin -u root create api_production
			mysqladmin -u root create webui_production
			mysqladmin -u root password "opensuse"
                        RUN_INITIAL_SETUP="true"
		fi
                if [ -n "$RUN_INITIAL_SETUP" ]; then
			echo -n "Initialize OBS api database (first time only)"
        		cd $apidir
			RAILS_ENV=production rake db:setup >> $apidir/log/db_migrate.log
                        ( umask 0077; dd if=/dev/urandom bs=256 count=1 2>/dev/null |sha256sum| cut -d\  -f 1 >config/secret.key )
			chmod 0640 config/secret.key
			chown root.www config/secret.key
		else
			echo
			echo -n "Migrate OBS api database"
			cd $apidir
			RAILS_ENV=production rake db:migrate >> $apidir/log/db_migrate.log
			echo
		fi
                if [ -n "$RUN_INITIAL_SETUP" ]; then
			echo -n "Initialize OBS webui database (first time only)"
        		cd $webuidir
			RAILS_ENV=production rake db:setup >> $webuidir/log/db_migrate.log
                        ( umask 0077; dd if=/dev/urandom bs=256 count=1 2>/dev/null |sha256sum| cut -d\  -f 1 >config/secret.key)
			chmod 0640 config/secret.key
			chown root.www config/secret.key
		else
			echo
			echo -n "Migrate OBS webui database"
			cd $webuidir
			RAILS_ENV=production rake db:migrate >> $webuidir/log/db_migrate.log
			echo
		fi

                # reuse signing key even if hostname changed
                if [ ! -e /srv/obs/certs/server.key ]; then
                    install -d -m 0700 /srv/obs/certs
                    openssl genrsa -out /srv/obs/certs/server.key 1024
                fi

                if [ ! -e /srv/obs/certs/server.${FQHOSTNAME}.created ]; then
                       # setup ssl certificates (NOT protected with a passphrase)
                       echo "Creating a default SSL certificate for the server, please replace it with your version in /obs/certs directory..."
                       # hostname specific certs - survive intermediate hostname changes
                       if [ ! -e /srv/obs/certs/server.${FQHOSTNAME}.pem ] ; then
                           # This is just a dummy SSL certificate, but it has a valid hostname. Admin can replace it with his version.
		           echo "CC
Test State or Province
Test Locality
Organization Name
Organizational Unit Name
$FQHOSTNAME
test@email.address


"                        | openssl req -new -key /srv/obs/certs/server.key -out /srv/obs/certs/server.${FQHOSTNAME}.csr >& /dev/null
                           openssl x509 -req -days 365 -in /srv/obs/certs/server.${FQHOSTNAME}.csr -signkey /srv/obs/certs/server.key -out /srv/obs/certs/server.${FQHOSTNAME}.crt
                           cat /srv/obs/certs/server.key /srv/obs/certs/server.${FQHOSTNAME}.crt > /srv/obs/certs/server.${FQHOSTNAME}.pem
                           echo "Do not remove this file or new SSL CAs will get created." > /srv/obs/certs/server.${FQHOSTNAME}.created
                       else
                         echo "ERROR: SSL CAs in /srv/obs/certs exists, but were not created for your hostname"
                         exit 1
                       fi
                fi
		# change links for certs according to hostnames
		rm /srv/obs/certs/server.crt /srv/obs/certs/server.pem
		ln -sf /srv/obs/certs/server.${FQHOSTNAME}.crt /srv/obs/certs/server.crt
		ln -sf /srv/obs/certs/server.${FQHOSTNAME}.pem /srv/obs/certs/server.pem

                cd $webuidir
		chown -R wwwrun.www $webuidir/log
                cd $apidir
		chown -R wwwrun.www $apidir/log

		cat > /etc/issue <<EOF
Welcome to Open Build Service(OBS) Appliance $OBSVERSION
based on $OS

EOF
		if ! grep -q "^our \$sign =" /usr/lib/obs/server/BSConfig.pm ; then
			cat >> /etc/issue <<EOF

  WARNING: **** Package signing is disabled, maybe due to lack of hardware number generator ****

EOF
		fi

		if [ -n "$FQHOSTNAME" ]; then
                        sed -e "s,___WEBUI_URL___,https://$FQHOSTNAME,g" \
                            -e "s,___API_URL___,https://$FQHOSTNAME:444,g" \
                            -e "s,___REPO_URL___,http://$FQHOSTNAME:82,g" \
                            /srv/www/obs/overview/overview.html.TEMPLATE > /srv/www/obs/overview/index.html

			cat >> /etc/issue <<EOF

  Connect to the web interface via:     https://$FQHOSTNAME
  Connect to the api interface via:     https://$FQHOSTNAME:444
  Browse the build packages via:        http://$FQHOSTNAME:82

 * "Admin"/"root" user password is "opensuse" by default.
 * Connect to the web interface now to finish the OBS setup.

More informations about this appliance are available here:

 http://en.opensuse.org/Build_Service/OBS-Appliance

                                  Greetings from the Open Build Service Team
                                  http://www.open-build-service.org

EOF
		else
                        echo "OBS appliance could not get setup, no network found" > /srv/www/obs/overview/index.html
			echo '**********************************************' >> /etc/issue
			echo '**           NETWORK SETUP FAILED           **' >> /etc/issue
			echo '**                                          **' >> /etc/issue
			echo '** OBS is not usable                        **' >> /etc/issue
			echo '** A working DHCP and DNS server in network **' >> /etc/issue
			echo '** is required!                             **' >> /etc/issue
			echo '**********************************************' >> /etc/issue
		fi
		rc_status -v
	;;
	stop)
                # nothing to do
		rc_status -v
	;;
	restart)
                # nothing to do
		rc_status
	;;
	try-restart)
                # nothing to do
		rc_status
	;;
	reload)
                # nothing to do
		rc_status
	;;
	status)
		# nothing to do
		rc_status -v
	;;
	*)
		echo "Usage: $0 {start|stop|status|try-restart|restart|reload}"
		exit 1
	;;
esac
rc_exit
