#!/bin/sh

# start this script with "osso-xterm -e" for screen output

#user='user'
#passwd='passwd'
## url without https://, e.g.
## my.server.com/owncloud
#oc_url='servername_and_path_to_your_oc'

logfile='/home/user/owncloud.log'
# uncomment next line to disable logging
#logfile='/dev/null'

cfgfile='/home/user/.simple_oc.cfg'

# https or http (not recommended)
protocol='https'

if [ -e $cfgfile ]
then
    . $cfgfile
else
    echo "### Initial configuration ###"
    echo "Please enter your owncloud base dir (e.g. /home/user/oc)"
    read oc_dir

    [ -d "$oc_dir" ] || {
	echo "Creating base dir $oc_dir"
	mkdir -p "$oc_dir"
    }

    echo "Please enter your username!"
    read user
    echo "Please enter your password!"
    echo "(Please be aware that it will be stored in plaintext."
    echo " It might also be visible in the logfile and in the"
    echo " process list while simple_oc is running)"
    read passwd
    echo "Please enter the oc url without https://"
    echo "(e.g. my.server.com/owncloud)!"
    read oc_url
    echo "Please enter the protocol (http or https)"
    read protocol

    touch $cfgfile
    chmod 700 $cfgfile
    echo "oc_dir='$oc_dir'" >> $cfgfile
    echo "user='$user'" >> $cfgfile
    echo "passwd='$passwd'" >> $cfgfile
    echo "oc_url='$oc_url'" >> $cfgfile
    echo "protocol='$protocol'" >> $cfgfile

    echo "The information is stored in the file"
    echo "$cfgfile"
    echo "Please delete this file to run this dialog again."
    echo "Press return to continue and start the first sync"
    read a

fi

touch $logfile
chmod 700 $logfile

protocol=$(echo "$protocol" | sed s/http/owncloud/)

{
    url="${protocol}://${user}:${passwd}@${oc_url}/remote.php/webdav"
    #echo "Synchronizing ${oc_dir} with ${url}"
    owncloudcmd "${oc_dir}" "${url}"
	
    retval=$?
    if [ $retval != 0 ]; then
	echo "owncloudcmd exited with return code $retval!"
	echo "Return to continue"
	read dummy
    else
	echo "owncloudcmd exited normally."
    fi
} 2>&1 | tee -a "$logfile"

