#!/bin/sh
# See also
# http://doc.owncloud.org/server/6.0/admin_manual/configuration/configuration_automation.html

if [ -e /etc/apache2/conf-enabled/owncloud.conf ] ; then
    owncloud_enable=true
else
    owncloud_enable=false
fi
owncloud_enable_cur=$owncloud_enable
export owncloud_enable


while [ "$1" ] ; do 
    arg="$1"
    shift
    case "$arg" in
	enable|noenable) # Not using disable for consistency with other options
	    if [ 'enable' = "$arg" ] ; then
		owncloud_enable=true
	    else
		owncloud_enable=false
	    fi
	    export owncloud_enable
	    ;;
	status)
	    printstatus() {
		if "$2" ; then
		    echo "$1"
		else
		    echo no"$1"
		fi
	    }
	    printstatus enable $owncloud_enable_cur
	    exit 0
	    ;;
	*)
	    ;;
    esac
done

if [ "$owncloud_enable" != "$owncloud_enable_cur" ] ; then
    if $owncloud_enable ; then
	# Select postgresql as the backend database for OwnCloud, and
	# make sure its php support is enabled when owncloud is
	# installed.
	DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends \
	    install -y postgresql php5-pgsql 2>&1 | logger -t owncloud-setup
	DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends \
	    install -y owncloud 2>&1 | logger -t owncloud-setup

	# Keep existing configuration if it exist
	if [ ! -e /etc/owncloud/config.php ] ; then
	    # Set up postgresql database and user
	    dbpwd=$(pwgen -1 30)
	    su - postgres -c "psql -c \"CREATE USER owncloud WITH NOCREATEDB NOCREATEUSER ENCRYPTED PASSWORD '$dbpwd'\"" \
		2>&1 | logger -t owncloud-setup
	    su - postgres -c "createdb --owner owncloud owncloud" \
		2>&1 | logger -t owncloud-setup

	    cat > /etc/owncloud/autoconfig.php <<EOF
<?php
\$AUTOCONFIG = array(
  'directory'     => '/usr/share/owncloud/data',
  'dbtype'        => 'pgsql',
  'dbname'        => 'owncloud',
  'dbuser'        => 'owncloud',
  'dbpass'        => '$dbpwd',
  'dbhost'        => 'localhost',
  'dbtableprefix' => 'oc_',

  'installed'     => false,
);
EOF
# The default admin user and password set up in owncloud
# FIXME figure out how to pick username and password, perhaps from the
# plinth user database?
#adminuser=admin
#adminpwd=secret
# Use these in autoconfig.php to set admin username and password:
#  'adminlogin'    => '$adminuser',
#  'adminpass'     => '$adminpwd',

	    a2enconf owncloud 2>&1 | logger -t owncloud-setup
	    service apache2 restart 2>&1 | logger -t owncloud-setup

	    # Initialize application and database tables by visiting
	    # the front page.  This only work if admin user and
	    # password was set above.
	    #wget --quiet http://$(uname -n)/owncloud/index.php
	else
	    a2enconf owncloud 2>&1 | logger -t owncloud-setup
	    service apache2 restart 2>&1 | logger -t owncloud-setup
	fi
    else
	a2disconf owncloud 2>&1 | logger -t owncloud-setup
	service apache2 restart 2>&1 | logger -t owncloud-setup
    fi
fi
