#!/bin/bash -e
# regenerate syncthing secrets by removing default config and restarting
# (syncthing will auto regenerate required files)

CONF_DIR=/home/syncthing/.local/state/syncthing

systemctl enable syncthing@syncthing.service || true
systemctl stop syncthing@syncthing.service || true

# create backups, just in case...
FILES="config.xml cert.pem cert.key https-cert.pem https-key.pem csrftokens.txt"
for file in ${FILES}; do
    file=${CONF_DIR}/${file}
    if [[ -f ${file} ]]; then
        mv ${file} ${file}.bak
    fi
done

systemctl start syncthing@syncthing.service

# Set up TurnKey default config

CONF=${CONF_DIR}/config.xml

# wait until conf file is present
while true; do
    if [[ -f ${CONF} ]]; then
        break
    else
        sleep 1
    fi
done

# add extra sleep to ensure that writing of config files is complete on low power systems
sleep 2

# remove default user(s) & password(s) (shouldn't be any with clean conf, but for good measure)
sed -i '\|<user>.*|d' $CONF
sed -i '\|<password>.*|d' $CONF

# add new default user 'syncthing' with (temporary) mcookie password (adjusted by inithook)
PASS=$(mcookie)$(mcookie)
sed -i '\|<address>[0-9].*</address>|a \\t<user>syncthing</user>' $CONF
# note extra \ redq for tab when wrapped in double quotes
sed -i "\|<user>syncthing</user>|a \\\t<password>${PASS}</password>" $CONF

# lock access to localhost, on non-standard port 8383 (reverse proxied by Nginx)
sed -i 's|<address>[0-9].*</address>|<address>127.0.0.1:8383</address>|g' $CONF
# disable TLS (aka SSL) - Nginx reverse proxy provides TLS (current default is false, but just in case)
sed -i 's|tls="true"|tls="false"|g' $CONF

# disable Syncthing's "Hostcheck" - as recommended by upstream: 
# https://github.com/syncthing/docs/issues/401#issuecomment-404088454
sed -i '\|<gui enabled|a \\t<insecureSkipHostcheck>true</insecureSkipHostcheck>' $CONF
