#!/bin/sh

GRAY="\e[0;30m"
RED="\e[0;31m"
GREEN="\e[0;32m"
YELLOW="\e[0;33m"
BLUE="\e[0;34m"
PURPLE="\e[0;35m"
CYAN="\e[0;36m"
WHITE="\e[0;37m"
RESET="\e[0m"

# install wordpress with cli : https://make.wordpress.org/cli/handbook/how-to-install/
# commands : https://developer.wordpress.org/cli/commands/

echo -e ${YELLOW}download wordpress :${RESET}
if ! wp core version --path="${WP_VOLUME_DIR}" 2> /dev/null
then
	mkdir -p ${WP_VOLUME_DIR}
		wp core download --path="${WP_VOLUME_DIR}" --allow-root
else
	echo -e ${GREEN}already there !${RESET}
fi

#	# create config file :
#	echo -e ${YELLOW}config wordpress :${RESET}
#	if ! wp config path --path="${WP_VOLUME_DIR}" --quiet 2> /dev/null
#	then
#		wp config create \
#			--dbhost="${DB_HOST}" \
#			--dbname="${DB_NAME}" \
#			--dbuser="${DB_USER}" \
#			--dbpass="${DB_PSWD}" \
#			--path="${WP_VOLUME_DIR}" --allow-root
#	else
#		echo -e ${GREEN}already configured !${RESET}
#	fi
#	
#	# install wordpress :
#	echo -e ${YELLOW}install wordpress :${RESET}
#	if ! wp core is-installed --path="${WP_VOLUME_DIR}" 2> /dev/null
#	then
#		wp core install \
#			--url="${WP_URL}" \
#			--title="${WP_TITLE}" \
#			--admin_user="${WP_ADMIN}" \
#			--admin_email="${WP_ADMIN_EMAIL}" \
#			--admin_password="${WP_ADMIN_PSWD}" \
#			--skip-email \
#			--path="${WP_VOLUME_DIR}" --allow-root
#	else
#		echo -e ${GREEN}already installed !${RESET}
#	fi
#	
#	# create user :
#	echo -e ${YELLOW}create wordpress user :${RESET}
#	if ! wp user get ${WP_USER} --path="${WP_VOLUME_DIR}" --field=login 2> /dev/null
#	then
#		wp user create \
#			"${WP_USER}" "${WP_USER_EMAIL}" \
#			--user_pass="${WP_USER_PSWD}" \
#			--path="${WP_VOLUME_DIR}" --allow-root
#	else
#		echo -e ${GREEN}already created !${RESET}
#	fi
#	
#	# change owner and permissions to wp files
#	chown -R www-data:www-data /var/www/*
#	chmod 755 -R /var/www/*
#	
#	# symlinks for folders found in host plugins/
#	plugins=$(ls ${WP_VOLUME_PLUGINS})
#	for dir in $plugins; do
#		ln -s ${WP_VOLUME_PLUGINS}/$dir ${WP_VOLUME_DIR}/wp-content/plugins/$dir
#	done

if ! wp core is-installed --path="${WP_VOLUME_DIR}" 2> /dev/null
then
	wp config create \
		--dbhost="${DB_HOST}" \
		--dbname="${DB_NAME}" \
		--dbuser="${DB_USER}" \
		--dbpass="${DB_PSWD}" \
		--path="${WP_VOLUME_DIR}" --allow-root
	wp core install \
		--url="${WP_URL}" \
		--title="${WP_TITLE}" \
		--admin_user="${WP_ADMIN}" \
		--admin_email="${WP_ADMIN_EMAIL}" \
		--admin_password="${WP_ADMIN_PSWD}" \
		--skip-email \
		--path="${WP_VOLUME_DIR}" --allow-root
	wp user create \
		"${WP_USER}" "${WP_USER_EMAIL}" \
		--user_pass="${WP_USER_PSWD}" \
		--path="${WP_VOLUME_DIR}" --allow-root

	chown -R www-data:www-data /var/www/*
	chmod 755 -R /var/www/*

	plugins=$(ls ${WP_VOLUME_PLUGINS})
	for dir in $plugins; do
		ln -s ${WP_VOLUME_PLUGINS}/$dir ${WP_VOLUME_DIR}/wp-content/plugins/$dir
	done
fi


exec "${PHP_VERSION}" -FR

