#!/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'

logdir='/home/user/.oc_log'
mkdir -p "$logdir"
find "$logdir" -mtime +30 -print0 | xargs -0 rm -f     

oldlogfile='/home/user/owncloud.log'
if [ -e $oldlogfile ]; then
    mv $oldlogfile "$logdir"
fi

logfile="$logdir"/`date +%s`

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

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

if [ -e $cfgfile ]
then
    . $cfgfile
    [[ "$options"x == x ]] && options="--silent"
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 "options=--silent" >> $cfgfile
    echo "#Known options:"
    echo "#   --silent               Don't be so verbose"
    echo "#   --confdir = configdir: Read config from there."
    echo "#   --httpproxy = proxy:   Specify a http proxy to use."
    echo "#                          Proxy is http://server:port"
    echo "#   --trust                Trust the SSL certification."

    echo "$cfgfile"
    echo "Please delete this file to run this dialog again."
    echo "You can also modify the file to specify owncloudcmd options."
    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}/"
    #should be removed in 1.6.1
    #remote.php/webdav
    #echo "Synchronizing ${oc_dir} with ${url}"
    owncloudcmd $options "${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"

