#!/bin/bash
#name:01-setup
#TODO clone the repo into /srv/gargantext/ and reduce the different steps
#git clone ssh://git@gitlab.iscpif.fr:20022/humanities/gargantext.git /srv/gargantext \
#        && cd /srv/gargantext \
#        && git fetch origin stable \
#        && git checkout stable
function clone_repo {
    echo "* CLONE"
    #echo "/home/"$USER"/ssh_keys/"$USER;
    read -e -r -p "Please provide you ssh keys full directory:" response;

    ssh-agent bash -c 'ssh-add ' $response '';
    git clone ssh://git@gitlab.iscpif.fr:20022/humanities/gargantext.git -o /srv/gargantext;
    cd /srv/gargantext
    git fetch origin stable
    git pull
    git checkout -b $USER'-stable';
    echo "Switching to your own branch";
}

function download_lib {
    echo "* DOWNLOAD  additionnal lib"
    echo "(May take a while, be patient or come back later when finished;)"
    sudo wget -P install/ http://dl.gargantext.org/gargantext_lib.tar.bz2
    #here gargantext_lib.tar.bz2 inside this directory
}

function uncompress_lib {
    cd /srv/gargantext/install/
    echo "* UNCOMPRESSING  additionnal lib"
    sudo tar xvjf gargantext_lib.tar.bz2 -o /srv/gargantext_lib
    sudo chown -R gargantua:gargantua /srv/gargantext_lib
}
#~ read -r -p "Do you want to clone the project? [y/N] " response
#~ case $response in
    #~ [yY][eE][sS]|[yY])
        #~ clone_repo
        #~ ;;
    #~ *)
        #~ cd /srv/gargantext/
        #~ ;;
#~ esac


echo "::: CREATE GROUP :::";
if grep -q 'gargantua' /etc/groups
then
    echo "Using existing group 'gargantua'"
else
    sudo groupadd gargantua
fi

# adding the users to the group
current_user=$(who -m | cut -d' ' -f1)
sudo usermod -G gargantua $current_user
sudo usermod -G gargantua gargantua

# changing the group of the sourcedir
sudo chown -R :gargantua /srv/gargantext

echo "::: SETUP ENV :::";
for dir in "/srv/gargantext_lib" "/srv/gargantext_static" "/srv/gargantext_media"; do
    sudo mkdir -p $dir ;
    sudo chown gargantua:gargantua $dir ;
done;
#here gargantext_lib.tar.bz2 inside this directory

#sudo wget http://dl.gargantext.org/gargantext_lib.tar.bz2 && \
#sudo tar xvjf gargantext_lib.tar.bz2 -o /srv/gargantext_lib \
#&& sudo chown -R gargantua:gargantua /srv/gargantext_lib \
#&& echo ":::::::::::::::::Done::::::::::::::::::::::::::";
echo ':::: BUILD ::::'
sudo docker build -t gargamelle:latest ./gargamelle
echo ':::: CONFIGURE ::::'

sudo docker run \
        --name=gargamelle_box \
        -v /srv/gargantext:/srv/gargantext \
        -v /srv/gargandata:/srv/gargandata \
        -v /srv/gargantext_lib:/srv/gargantext_lib \
        -p 8000:8000 \
        -p 5432 \
        -it gargamelle:latest \
        /bin/bash -c "./psql_configure.sh; ./django_configure.sh ; exit"

sudo docker rm gargamelle_box

# creating the "start" copy + giving it normal ownership (because we're probably sudo)
cp ./run /srv/gargantext/start
chown $current_user:gargantua /srv/gargantext/start
