init() {
    for dir in frontend backend out; do
        if [ ! -d $dir ]; then
            mkdir $dir
            if [ $dir != "out" ]; then
                echo Cloning $dir
                git clone https://mhsl.eu/gitea/TheAdversary/$dir.git
            fi
        fi
    done
}

build() {
    pwd=$PWD
    cd out/backend/
    go build .
    cp -rf TheAdversary database.sqlite3 ../
    if [ ! -f  ../../.env ]; then
        cp -rf .env ../
    else
        cp ../../.env ../
    fi
    cd $pwd
}

start() {
    pwd=$PWD
    cd out/
    ./TheAdversary
    cd $pwd
}

stop() {
    kill $(pidof TheAdversary)
}

process() {
    sleep 5

    cp -rf frontend/ backend/ out/
    build
    echo "Restarting"
    stop
    start &
}

main() {
    init
    cp -rf frontend/ backend/ out/
    build
    if [ $? -eq 0 ]; then
        start &
    fi

    while inotifywait -r -e modify frontend/ backend/; do
        if [ -d /proc/$! ]; then
            kill $!
        fi
        process &
    done
}

main
