#!/bin/bash
#
#    common - Common functions
#
#    Copyright (C) 2012  Marco Ceppi
#    Author: Marco Ceppi <marco@ceppi.net>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

hostname=`unit-get public-address`
private_name=`hostname --all-fqdns | cut -f 1 -d ' '`

wp_install_path="/var/www"
config_file_path="$wp_install_path/wp-config.php"
config_info_path="$wp_install_path/wp-info.php"
config_override_path="$wp_install_path/wp-overrides.php"

####
## The only hook who should ever remove the NFS mount is the nfs-relation-(departed|broken) hook
## Everyone else should just assume it's there or try to mount it. We don't want to loose people's
## data, they get mad when that happens :(
####

engine()
{
	echo `cat .web-engine`
}

total_memory()
{
  echo $((`awk '/MemTotal/{print $2}' /proc/meminfo` / 1024))
}

apc_shm_size()
{
  all_memory=`total_memory`
  if [ -z $all_memory ]; then
    echo 256 # Play it safe, no memory was reported.
    return 0
  fi

  if [ $all_memory -gt 1280 ]; then
    echo 1024
  else
    echo $((all_memory * 80 / 100))
  fi
}

make_bare()
{
	# Un-do APC
	rm -f /etc/php5/conf.d/apc.ini
	# IF there is an NFS mount, get everything out of it
	if [ -f .nfs-mount ]; then # Looks like someone got fancy with NFS
		if [ -L $wp_install_path/wp-content ]; then # Check if we actually have a symlink
			rm -f $wp_install_path/wp-content
			rsync -az /mnt/wordpress/wp-content $wp_install_path
		fi
	fi

	echo "<?php" > $config_override_path
	juju-log "We are now bare"
}

make_single()
{
	make_bare
	juju-log "Installing PHP apc.ini ..."
	rm -f /etc/php5/conf.d/apc.ini
	install -o root -g root -m 0644 files/charm/php/php5_conf.d_apc.ini /etc/php5/conf.d/apc.ini

	shm_size=`apc_shm_size`
	sed -i -e "s/^apc\.shm_size=.*$/apc.shm_size=${shm_size}M/" /etc/php5/conf.d/apc.ini

	## We do NFS here, because Configuration changes cascade. So to get to Optimzied you *must* first 
	## make "single" (and by association, "bare"). Since nfs is both a single and optimized thing we do it now.

	do_nfs

	juju-log "We are now single, ALL THE SINGLE UNITS ALL THE SINGLE UNITS"
}

make_optimized()
{
	make_single
	cat > $config_override_path <<EOF
<?php
define('DISALLOW_FILE_MODS', TRUE);
EOF
	juju-log "We are now optimized prime"
}

do_nfs()
{
	if [ -f .nfs-mount ]; then
		# This has all the NFS mount stuff in it
		source .nfs-mount
		mkdir -p /mnt/wordpress
		if grep -qs '/mnt/wordpress' /proc/mounts; then
			juju-log "We're already mounted."
		else
			mount -t $MOUNT_TYPE $MOUNT_OPS $MOUNT_SERVER:$MOUNT_PATH /mnt/wordpress
			if [ $? -ne 0 ]; then
				juju-log "Could not connect to file-server"
				exit 1 # OH THE HUMANITY OF IT ALL
			fi
			if [ ! -d /mnt/wordpress/wp-content ]; then
				rsync -az $wp_install_path/wp-content /mnt/wordpress/
			fi

			mv $wp_install_path/wp-content $wp_install_path/wp-content.bak.$(date +%Y%m%d-%H%M%S) && rm -rf $wp_install_path/wp-content
			ln -s /mnt/wordpress/wp-content $wp_install_path
			juju-log "Mounted NFS"
		fi
	else
		juju-log "There is no nfs mount, not sure what to do, so we'll just bail"
	fi
}

do_vcs()
{
	source "/usr/share/charm-helper/bash/vcs.bash"

	local NEW_REPO_URL=${1:-""}

	if [ -z "$NEW_REPO_URL" ]; then
		rm -f .wp-repo
		return 0
	fi

	if [ -f .wp-repo ]; then
		source .wp-repo
	else
		REPO_URL=""
	fi

	if [ "$NEW_REPO_URL" != "$REPO_URL" ]; then
		# We need to determine what kind of URL this is

		repo_path=`ch_fetch_repo $NEW_REPO_URL`
		if [ $? -ne 0 ]; then
			juju-log "Failed to fetch repo, charm-helper/bash/vcs.bash exited with $?"
			return 1
		fi

		# Write all our new data to disk
		cat > .wp-repo <<EOF
#!/bin/bash
REPO_URL=$NEW_REPO_URL
REPO_PATH=$repo_path
EOF
		source .wp-repo # Just so the rest of this can run all willy nilly
	else
		# Lets just try and do a fetch
		ch_update_repo "$REPO_PATH"
		if [ $? -ne 0 ]; then
			juju-log "Failed to update repository, charm-helper/bash/vcs.bash exited with $?"
			return 2
		fi
	fi

	repo_type=`ch_detect_vcs $REPO_PATH`

	if [ ! -d "$REPO_PATH/wp-content" ]; then
		# This is just someone who has their source control at the root level of the repo.
		wp_content_path="$REPO_PATH/wp-content"
		rsync -az --delete --exclude ".$repo_type/*" $REPO_PATH/ $wp_install_path/wp-content/
	else
		# This is a repo with a wp-content folder. So we'll move that then everything else they have in that repo
		# to the web root. OMG requirement.
		rsync -az --delete --exclude ".$repo_type/*" $REPO_PATH/wp-content/ $wp_install_path/wp-content/
		# This is just incase people have modifications outside of the wp-content directory
		rsync -az --exclude ".$repo_type/*" $REPO_PATH/ $wp_install_path/
	fi
}

do_cache()
{
	if [ ! -f .memcache ]; then
		if [ -d $wp_install_path/wp-content/plugins/wp-ffpc ]; then
			wp plugin uninstall --path=$wp_install_path wp-ffpc
			wp plugin delete --path=$wp_install_path wp-ffpc
		fi

		return 0
	fi

	source .memcache

	wp plugin install --path=$wp_install_path wp-ffpc
	sed -i -e "s/'host'=>.*/'host'=>'$CACHE_HOST',/" $wp_install_path/wp-content/plugins/wp-ffpc/wp-ffpc.php
	wp plugin activate --path=$wp_install_path wp-ffpc

	install -o www-data -g www-data -m 0644 files/charm/wordpress/advanced-cache.php $wp_install_path/wp-content/advanced-cache.php
	sed -i -e "s/\$wp_ffpc_config\['host'\]=.*/\$wp_ffpc_config\['host'\]='$CACHE_HOST';/" \
		-e "s/\$wp_ffpc_config\['port'\]=.*/\$wp_ffpc_config\['host'\]='$CACHE_PORT';/" \
		$wp_install_path/wp-content/advanced-cache.php

	engine=`cat .web-engine`
	if [ "$engine" == "nginx" ]; then
		sed -i -e "s/memcached_pass .*/memcached_pass $CACHE_HOST\:$CACHE_PORT;/" /etc/nginx/sites-enabled/wordpress
	fi
}
