#!/bin/bash

source /usr/local/etc/library.sh # sets PHPVER

set -e

[[ "$1" == "stop" ]] && {
  echo "Stopping apache"
  apachectl graceful-stop
  echo "Stopping PHP-fpm"
  pkill -f php-fpm
  echo "Stopping mariaDB"
  mysqladmin -u root shutdown
  echo "LAMP cleanup complete"
  exit 0
}

# MOVE CONFIGS TO PERSISTENT VOLUME
persistent_cfg /etc/apache2/sites-available /data/etc/apache2/sites-available
persistent_cfg /etc/apache2/sites-enabled /data/etc/apache2/sites-enabled

# Run hardcoded hooks. This allows scripts in the image to change persistent values before
# initialization. Use case is to download a new image.
if [[ -f /usr/local/bin/ncp-docker-hook ]]; then
  source /usr/local/bin/ncp-docker-hook
fi

echo "Starting PHP-fpm"
clear_opcache
php-fpm"${PHPVER}"

echo "Starting Apache"
/usr/sbin/apache2ctl start

# adjust the dbdir to the persistent storage
install_template "mysql/90-ncp.cnf.sh" "/etc/mysql/mariadb.conf.d/90-ncp.cnf" || exit 1

# start
echo "Starting mariaDB"
mysqld &

# wait for mariadb
while :; do
  [[ -S /run/mysqld/mysqld.sock ]] && break
  sleep 0.5
done
sleep 1

exit 0
