#!/bin/sh
#
# Sascha Peilicke <saschpe@mailbox.org>
#
# Wrapper script around /usr/bin/btsync that generates a 
# suitable default configuration if it's not present already.
# For the root user, it's put at /etc/btsync.conf and uses 
# system-wide paths (such as /var/lib/btsync). Non-root users
# get a $HOME/.btsync.conf file and a $HOME/.sync working dir.
#

if [[ $EUID -eq 0 ]]; then
    STOR_PATH=/var/lib/btsync
    CONF_FILE=/etc/btsync.conf
else
    STOR_PATH=$HOME/.btsync
    CONF_FILE=$STOR_PATH/sync.conf
fi

if [ ! -f $CONF_FILE ] ; then
    if [[ $EUID -ne 0 ]]; then
        mkdir -p $STOR_PATH
    fi
    /usr/bin/btsync --dump-sample-config > $CONF_FILE
    sed -i \
        -e "s|\"password\" : \"password\"|\"password\" : \"$(date +%s | sha256sum | base64 | head -c 32)\"|" \
        -e "s|\"device_name\": \"My Sync Device\"|\"device_name\": \"$(hostname -f)\"|" \
        -e "s|\"login\" : \"admin\"|\"login\" : \"$USER\"|" \
        -e "s|\"secret\" : \"MY_SECRET_1\"|\"secret\" : \"$(btsync --generate-secret)\"|" \
        -e "s|\"listen\" : \"0.0.0.0:8888\"|\"listen\" : \"0.0.0.0:$(expr 8888 + $EUID)\"|" \
        -e "s|\"storage_path\" : \"/home/user/.sync\"|\"storage_path\" : \"$STOR_PATH\"|" \
        -e "/\/\/ \"pid_file.*/d" \
        -e "/\/\/ uncomment next.*/d" $CONF_FILE
fi

exec /usr/bin/btsync --nodaemon --config $CONF_FILE
