#!/bin/sh
set -e

# Save config and data under the KOReader runtime directory
config_dir=settings/syncthing
data_dir=/var/local/syncthing
syncthing=plugins/syncthing.koplugin/syncthing
pid_file=/tmp/syncthing_koreader.pid

if [ -n "$1" ]; then
    home_dir=$1
else
    home_dir=/
fi


if [ -n "$2" ]; then
    port=$2
else
    port=8384
fi

if [ -n "$3" ]; then
    password=$3
fi

if [ ! -f "$config_dir/config.xml" ] || [ -n "$password" ]; then
    echo "Generating Syncthing configuration..."
    # Set HOME so that the default folder is created at $home_dir/Sync
    HOME=$home_dir "$syncthing" generate \
        --data="$data_dir" \
        --config="$config_dir" \
        --gui-user=syncthing \
        --gui-password="$password" \
        --no-port-probing # Need this due to lack of IPv4 loopback in Kobo
fi

if [ ! -f "$config_dir/device-id" ]; then
    # Save the device ID to a file for easy access from KOReader
    "$syncthing" \
        --config="$config_dir" \
        --data="$data_dir" \
        --device-id > "$config_dir/device-id"
fi

# We need to listen to 0.0.0.0 so that the GUI is accessible over the network
"$syncthing" serve \
    --config="$config_dir" \
    --data="$data_dir" \
    --gui-address=http://0.0.0.0:$port \
    --logfile="$config_dir/logs" \
    --log-max-old-files=10 \
    --log-max-size=1048576 &

# Write the PID to be used for stopping Syncthing later
echo $! > "$pid_file"
