#!/bin/bash

#    build_mumble_web.sh
#    Copyright (C) 2020  Armin Co
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.



# Mumble-Web repository
REPOSITORY="mumble-web"
URL_GITHUB="https://github.com/Johni0702/${REPOSITORY}.git"
# name of the image which will be build
IMAGE_NAME="build_mumble_web_image"
# name of the temporarily created container
CONTAINER_NAME="build_mumble_web_container"
# path to the directorie "dist" in the image
DIST_DIR="/home/node/dist"
# path on the host where to copy the files
DESTINATION_HOST="./dist"

function verify_commit_HEAD() {
    cd $REPOSITORY
    git verify-commit -v HEAD
    cd ../
}

echo "buildung mumble-web"
echo "files will be stored at:  ${DESTINATION_HOST}"

# check if git repository is already cloned
# then pull updates
# if not clone repository
if cd $REPOSITORY
then
    echo "updating mumble-web repository"
    git pull
    cd ../
else
    echo "cloning mumble-web repository"
    git clone $URL_GITHUB
fi

# print verify-commit output
verify_commit_HEAD

# build docker image 
echo "building mumble-web image"
echo "logs will be stored in: build.log"
time docker build --target mumble-web -t "${IMAGE_NAME}" . > build.log
# create temporary container
docker create --name $CONTAINER_NAME "${IMAGE_NAME}"
# remove previously copied files
rm -rf dist
# # copy files from container to host
docker cp $CONTAINER_NAME:"${DIST_DIR}" $DESTINATION_HOST
# remove created container
docker rm -f $CONTAINER_NAME
docker rmi $IMAGE_NAME