#!/bin/bash

set -e
role=${CONTAINER_ROLE:-app}
env=${APP_ENV:-live}
php=${PHP_DIR:-/var/www/html}
composer=${COMPOSER_DIR:-/var/www/.composer}

NO_NGINX=${NO_NGINX:-TRUE}
SSH_START=${SSH_START:-FALSE}

# To run a local queue, running jobs from the queue "hostname"
LOCAL_QUEUE=${LOCAL_QUEUE:-FALSE}
#LOCAL_QUEUES=	Optional additional queues to run for

function mp() {
	set +e
	mountpoint -q $1
	local mp=$?
	set -e
	echo ${mp}
}

function nginx_start() {
	# Start NGINX
	if [ -x /usr/sbin/nginx -a "${NO_NGINX}" != "TRUE" ]; then
		echo "* Starting NGINX..."
		start-stop-daemon --start --pidfile /var/run/nginx.pid --exec /usr/sbin/nginx -- -g 'daemon on; master_process on;'
	fi
}

# General Setup
if [ -x /usr/sbin/sshd -a "${SSH_START}" = "TRUE" ]; then
	[ ! -d /var/run/sshd ] && mkdir /var/run/sshd
	start-stop-daemon --start --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- -p 22
fi

# Laravel Specific
if [ "${role}" = "app" -a -e artisan ]; then
	if [ ! -e ${php}/.env ]; then
		echo "! ERROR: NO .env file..."
		exec /bin/bash
	fi

	mp=$(mp ${php})

	# Only adjust perms if this is an external mountpoint
	if [ ${mp} -eq 0 -o -n "${FORCE_PERMS}" ] ; then
		if [ -n "${FORCE_PERMS}" -o "${env}" != "dev" -a -z "${SKIP_PERM}" ]; then
			echo "* Setting Permissions..."
			# Make sure our permissions are appropraite
			find ${php} -type f -exec chmod 640 {} \;
			find ${php} -type d -exec chmod 750 {} \;
			chmod o+rx ${php}
			chmod -R o+rx ${php}/public
			chown -R lamp:www-data ${php}
			chown -R www-data:www-data ${php}/storage ${php}/bootstrap ${php}/composer.*
			[ -e ${php}/vendor ] && chown -R www-data:www-data ${php}/vendor
		fi
	fi

	if [ "${env}" != "local" -a -r "artisan" ]; then
		# See if we need to refresh our dependancies
		if [[ -r composer.json && ( -e .composer.refresh || ! -d vendor ) ]]; then
			rm -f ${php}/bootstrap/cache/*.php
			if [ "${env}" != "dev" ]; then
				NODEV="--no-dev"
			fi

			mp=$(mp ${composer})

			if [ ${mp} -eq 0 -o -n "${FORCE_PERMS}" ] ; then
				[ -n "${FORCE_PERMS}" -o "${env}" != "dev" -a -z "${SKIP_PERM}" ] && chown -R www-data:www-data ${composer}
				[ ! -d ${php}/vendor ] && mkdir -m 750 ${php}/vendor && chown www-data:www-data ${php}/vendor
				[ -n "${FORCE_PERMS}" -o "${env}" != "dev" -a -z "${SKIP_PERM}" ] && chmod g+w ${php}
			fi

			su www-data -s /bin/sh -c "composer install --optimize-autoloader ${NODEV}" && ( test -e .composer.refresh && rm -f .composer.refresh )
			[ -n "${FORCE_PERMS}" -o "${env}" != "dev" -a -z "${SKIP_PERM}" ] && [ ${mp} -eq 0 ] && chmod g-w ${php}
		fi

		if [ -e .lumen ]; then
			echo "* Lumen detected..."
		else
			echo "* Caching configuration..."
			su www-data -s /bin/sh -c "(php artisan config:cache && php artisan route:cache && php artisan view:cache)"
		fi

		if [ -r .migrate ]; then
			echo "* Running migration..."
			# If DB_HOST not set, source the env file
			[ -z "${DB_HOST}" -a -r .env ] && . .env

			if [ -n "${DB_HOST}" -a -n "${DB_PORT}" ]; then
				while ! wait-for-it -h ${DB_HOST} -p ${DB_PORT} -t 5 -q; do
					echo "? Waiting for database at ${DB_HOST}:${DB_PORT}"
					sleep 1;
				done
				echo "- DB is active on ${DB_HOST}:${DB_PORT}"
			fi

			su www-data -s /bin/sh -c "php artisan migrate" && rm -f .migrate
		fi

		# If passport is installed
		if [ -d ${php}/vendor/laravel/passport ]; then
			echo "* Generating OAUTH keys ..."
			su www-data -s /bin/sh -c "php artisan passport:keys"
		fi
	fi

	nginx_start
	if [ "${LOCAL_QUEUE}" = "TRUE" ]; then
		echo "* Starting local queue for [${LOCAL_QUEUES}]..."
		su www-data -s /bin/sh -c "
		(while true; do php ${PHP_OPTIONS} artisan queue:work --verbose --tries=${WORK_TRIES:-1} --timeout=${WORK_TIMEOUT:-90} --queue=$(hostname)${LOCAL_QUEUES:+,${LOCAL_QUEUES}} ${WORK_MEMORY:+--memory=${WORK_MEMORY}} ${WORK_ONCE:+--once}; done) &
		"
	fi

	exec /usr/local/bin/docker-php-entrypoint "$@"

elif [ "$role" = "queue" -a -e artisan ]; then
	if [ ! -e ${php}/.env ]; then
		echo "! ERROR: NO .env file..."
		exec /bin/bash
	fi

	QUEUE_CMD=work
	if [ "${env}" == "dev" ]; then
		QUEUE_CMD=listen
	fi

	if [ -e .lumen ]; then
		echo "* Lumen detected..."
	else
		# We only check for non mount points, in case this container has the app inside
		mp=$(mp ${php})
		if [ ${mp} -eq 1 ]; then
			echo "* Caching configuration..."
			su www-data -s /bin/sh -c "(php artisan config:cache && php artisan route:cache && php artisan view:cache)"
		fi
	fi

	echo "* Running the queue..."
	# We'll delay starting in case the app is caching
	sleep 15

	su www-data -s /bin/sh -c "
	while true; do
		php ${PHP_OPTIONS} artisan queue:${QUEUE_CMD} --verbose --tries=${WORK_TRIES:-1} --timeout=${WORK_TIMEOUT:-90} ${WORK_QUEUES:+--queue=${WORK_QUEUES}} ${WORK_MEMORY:+--memory=${WORK_MEMORY}} ${WORK_ONCE:+--once}
	done
	"

elif [ "$role" = "scheduler" -a -e artisan ]; then
	if [ ! -e ${php}/.env ]; then
		echo "! ERROR: NO .env file..."
		exec /bin/bash
	fi

	if [ -e .lumen ]; then
		echo "* Lumen detected..."
	else
		# We only check for non mount points, in case this container has the app inside
		mp=$(mp ${php})
		if [ ${mp} -eq 1 ]; then
			echo "* Caching configuration..."
			su www-data -s /bin/sh -c "(php artisan config:cache && php artisan route:cache && php artisan view:cache)"
		fi
	fi

	echo "* Running the scheduler..."
	# We'll delay starting in case the app is caching
	sleep 15

	su www-data -s /bin/sh -c "
	while true; do
		(php ${PHP_OPTIONS} artisan schedule:run --verbose --no-interaction &)
		sleep 60
	done
	"

else
	nginx_start

	echo "? NO container role \"${role}\", AND/OR no laravel install, just starting php-fpm"
	exec /usr/local/bin/docker-php-entrypoint "$@"
fi