#!/bin/bash

##################################################
# Mount dir                                      #
# - LOG_DIR                                      #
# - DATA_DIR                                     #
# ENV                                            #
# - EXTRA_ARGS                                   #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

PIDS=
GOT_SIGTERM=
LOG_DIR='/var/log/svn'
DATA_DIR='/var/lib/svn'

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    Print killing svnserve ...
    while :; do
        pkill -f svnserve && Print killing svnserve ... || break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function StartProc {
    Print Starting svn ${EXTRA_ARGS:-} ...
    svnserve \
        ${EXTRA_ARGS:-} \
        -d --foreground \
        -r $DATA_DIR \
        --listen-port 3690 \
        --pid-file /var/run/svn.pid \
        --log-file $LOG_DIR/svn.log \
        &>> $LOG_DIR/svn.out &
    PIDS="$PIDS $!"
    Print Svn started.
}

function Main {
    local pid=
    StartProc
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    while [ -z "$GOT_SIGTERM" ] && sleep 2; do
        for pid in $PIDS; do
            [ ! -e /proc/$pid ] && Print Unexpected error! && exit
        done
    done
}

# Start here
Main

