variables:
    GIT_SUBMODULE_STRATEGY: recursive

stages:
    - build
    - push
    - deploy

before_script:
    - docker --version
    - docker-compose --version

build:
    stage: build
    script:
        - echo "__branch__ = '${CI_COMMIT_REF_NAME}'"                                       >  ./web/app/version.py
        - echo "__commit__ = '${CI_COMMIT_SHA}'"                                            >> ./web/app/version.py
        - echo "__commiturl__ = '${CI_PROJECT_URL}/commit/${CI_COMMIT_SHA}'"                >> ./web/app/version.py
        - echo "__treeurl__ = '${CI_PROJECT_URL}/tree/${CI_COMMIT_SHA}'"                    >> ./web/app/version.py
        - echo "__date__ = '$(git show -s --format=%ci $CI_COMMIT_SHA)'"                    >> ./web/app/version.py
        - echo "__version__ = __branch__ + ' - ' + __commit__[ 0:8 ] + ' - ' + __date__ "   >> ./web/app/version.py
        - echo "__author_name__ = '$(git show -s --format=%an $CI_COMMIT_SHA)'"             >> ./web/app/version.py
        - echo "__author_email__ = '$(git show -s --format=%ae $CI_COMMIT_SHA)'"            >> ./web/app/version.py
        - echo "__author__ = __author_name__ + ' <' + __author_email__ + '>'"               >> ./web/app/version.py
        - make fromtemplate
        - make build

push:
    stage: push
    only:
        - master
        - develop
    script:
        - make push

deploy_master:
    stage: deploy
    only:
        - master
    script:
        - echo Deploying production on ${PROD_HOST}...
        - docker -H ${PROD_HOST} service update --force --detach --image=cr.unil.ch/icnml_web:${CI_COMMIT_SHORT_SHA} icnml_web

deploy_develop:
    stage: deploy
    only:
        - develop
    script:
        - eval $(ssh-agent -s)
        - echo "$SSH_CONFIGURATION_KEY" | tr -d '\r' | ssh-add - > /dev/null
        - ssh-add -l
        - git config --global user.name "$(git show -s --format=%an $CI_COMMIT_SHA)"
        - git config --global user.email "$(git show -s --format=%ae $CI_COMMIT_SHA)"
        - DEVDIR=$(mktemp -d)
        - git clone ${DEV_REPO} $DEVDIR 
        - cd $DEVDIR
        - git remote show origin
        - sed -i "s/cr.unil.ch\/icnml_web.*$/cr.unil.ch\/icnml_web\:${CI_COMMIT_SHORT_SHA}/g" docker-compose.yml
        - git add docker-compose.yml
        - git commit -m "Container update" -m "Update the docker image of ICNML to ${CI_COMMIT_SHORT_SHA} from the ${CI_PROJECT_URL} repository. Check the source at ${CI_PROJECT_URL}/commit/${CI_COMMIT_SHA}" -m "Regards, the CICD"
        - git push
