#!/bin/sh
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

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

grep -q "^\s*['\"]dbtype['\"]" /etc/owncloud/config.php 2> /dev/null
db_in_config=$(( ! $? ))

grep -q "^\s*['\"]dbtype['\"]" /etc/owncloud/autoconfig.php 2> /dev/null
db_in_autoconfig=$(( ! $? ))

if [ -e /etc/apache2/conf-enabled/owncloud.conf ] && \
       [ $db_in_config -ne 0 -o $db_in_autoconfig -ne 0 ] ; then
    owncloud_enable_cur=true
else
    owncloud_enable_cur=false
fi


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
	    ;;
	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
	# Keep existing configuration if it exist
	if [ $db_in_config -eq 0 -a $db_in_autoconfig -eq 0 ] ; then
	    # Set up postgresql database and user
	    dbpwd=$(pwgen -1 30)
	    su - postgres -c "psql -c \"CREATE USER owncloud WITH NOCREATEDB NOCREATEUSER\"" \
		2>&1 | logger -t owncloud-setup
	    su - postgres -c "psql -c \"ALTER USER owncloud 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
	fi

	a2enconf owncloud 2>&1 | logger -t owncloud-setup
    else
	a2disconf owncloud 2>&1 | logger -t owncloud-setup
    fi

    service apache2 reload 2>&1 | logger -t owncloud-setup
fi
