#!/bin/bash

set -e
cd $(dirname $0)/..

if [ -z $RESTARTED ]
then

    echo "# pull newest bigblugbutton-docker.git"
    git pull

    # restart script, since it might have changed.
    RESTARTED=1 ./scripts/upgrade
    exit

else

    echo ""
    echo "# recreate docker-compose.yml"
    ./scripts/generate-compose


    echo ""
    echo "# checking for old volumes & migrate them"
    COMPOSE_PREFIX=$(docker compose config | grep '^name:' | awk '{print $2}')
    
    function migrate_vol {
        VOLUME=${COMPOSE_PREFIX}_${1}
        EXISTING=$(docker volume ls | grep $VOLUME | tail -n1 | awk '{print $2}')
        if [ -n "$EXISTING" ]; then
            # ensure volume is not used
            docker compose down --remove-orphans
            
            echo "Migrating $VOLUME to $2"
            docker run --rm -v $VOLUME:/src -v $2:/dest --entrypoint /bin/sh eeacms/rsync -c 'rsync -av /src/ /dest'
            docker volume rm $EXISTING
        fi  
    }
    migrate_vol bigbluebutton ./data/bigbluebutton
    migrate_vol vol-freeswitch ./data/freeswitch-meetings
    migrate_vol vol-mediasoup ./data/mediasoup

    if [ -d "./postgres-data" ]; then
        echo "folder ./postgres-data still exists and probably uses postgres 12. migrating to a fresh postgres 16 data directory..."
        docker compose down --remove-orphans
        ./scripts/postgres-migrate ./postgres-data ./data/postgres 16
        mv postgres-data postgres-data.automigrate-bak
    fi

    if [ -d "./greenlight-data" ]; then
        if [ -d "./data/greenlight" ]; then
            mv ./data/greenlight ./data/greenlight.automigrate-bak
        fi
        mv ./greenlight-data ./data/greenlight
    fi

    # TODO: ask for LETSENCRYPT_EMAIL

    echo ""
    echo "# pull newest images"
    docker compose pull --ignore-pull-failures
    

    COMMIT_HASH=$(git rev-parse --short HEAD)
    BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)

    echo ""
    echo "-------------------------------------"
    echo "update is ready!"
    echo "we are on $COMMIT_HASH ($BRANCH_NAME)"
    echo ""
    echo "use following command for restarting bbb:"
    echo "    $ docker compose up -d --no-build"
    echo "-------------------------------------"
fi