#!/bin/bash

set -eu

juju-log "We've got a db"

source inc/common

if [ -f "$config_file_path" ]; then
	# No longer to quietly in to that good night. Update the wp-config file with new DB values
	juju-log "WordPress is already setup, just silently going away"
	exit 0
fi

database=`relation-get database`
user=`relation-get user`
password=`relation-get password`
host=`relation-get private-address`

if [ -z "$database" ] ; then
	exit 0
fi

source "/usr/share/charm-helper/sh/net.sh"

payload=`ch_get_file "https://wordpress.org/latest.tar.gz" "https://wordpress.org/latest.tar.gz.sha1"`

if [ ! -f "$payload" ] || [ -z "$payload" ]; then
	juju-log "Failed to retrieve latest.tar.gz"
	exit 1
fi

juju-log "Extract ALL THE FILES!"
tar -xzf $payload

mkdir -p $wp_install_path

juju-log "Move them in to place, but just 'drop' them in place."
rsync -az wordpress/ $wp_install_path

juju-log "Clean up"
rm -rf wordpress

secret_key=`cat .wp-secret`

juju-log "Writing wordpress config file $config_file_path"
# Write the wordpress config
cat > $config_info_path <<EOF
<?php
define('DB_NAME', '$database');
define('DB_USER', '$user');
define('DB_PASSWORD', '$password');
define('DB_HOST', '$host');
define('SECRET_KEY', '$secret_key');

define('WP_CACHE', true);

/*
define('AUTH_KEY', '$secret_key');
define('SECURE_AUTH_KEY', '$secret_key');
define('LOGGED_IN_KEY', '$secret_key');
define('NONCE_KEY', '$secret_key');
*/

\$table_prefix  = 'wp_';

EOF

cat > $config_file_path <<EOF
<?php

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

/** Pull in the config information */
require_once(ABSPATH . 'wp-info.php');
require_once(ABSPATH . 'wp-overrides.php');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

remove_filter('template_redirect', 'redirect_canonical');

EOF

chmod 0644 $config_file_path
touch $config_override_path

juju-log "Resetting permissions"

chown -R www-data.www-data $wp_install_path

. hooks/config-changed
. hooks/restart

# Make it publicly visible, once the wordpress service is exposed
open-port 80/tcp
