variables:
  WAR_FILE: target/arsnova-backend-*.war

stages:
  - analysis
  - test
  - build
  - deploy

cache:
  paths:
    - .m2/

sonar:
  stage: analysis
  only:
    - master
  tags:
    - maven
  allow_failure: true
  script:
    - mvn sonar:sonar

checkstyle:
  stage: analysis
  tags:
    - maven
  script:
    - mvn checkstyle:checkstyle

test:
  stage: test
  tags:
    - maven
  script:
    - mvn test

package:
  stage: build
  tags:
    - maven
  artifacts:
    paths:
      - $WAR_FILE
  script:
    - mvn package -DskipTests

.deploy: &deploy
  stage: deploy
  tags:
    - python
  when: manual
  variables:
    DEPLOY_CONTEXT: api
    GIT_STRATEGY: none
  script:
    # Do some variable magic to access host-specific variables
    - PREFIX=$(echo $CI_ENVIRONMENT_NAME | tr '.:/-' '_')
    - HOST_VAR=${PREFIX}__HOST TOMCAT_PASSWORD_VAR=${PREFIX}__TOMCAT_PASSWORD TOMCAT_USER_VAR=${PREFIX}__TOMCAT_USER
    - "[ -z \"${!HOST_VAR}\" ] && echo \"No configuration for $DEPLOY_HOST found.\" && exit 1"
    # Abort if there are too many users online
    - USER_COUNT=$(curl -fsSL ${CI_ENVIRONMENT_URL}statistics | python -c "import sys, json; data=json.loads(sys.stdin.read()); print(data['activeUsers']);")
    - "[ \"$USER_COUNT\" -ge 10 ] && [ -z \"$FORCE\" ] && echo \"Too many users ($USER_COUNT) online.\" && exit 1"
    # Deploy .war file to Tomcat
    - curl -fsS --upload-file $WAR_FILE "https://${!TOMCAT_USER_VAR}:${!TOMCAT_PASSWORD_VAR}@${!HOST_VAR}/manager/text/deploy?path=%2F${DEPLOY_CONTEXT}&update=true"

tomcat_production:
  <<: *deploy
  environment:
    name: production/$PROD_DEPLOY_HOST
    url: https://$PROD_DEPLOY_HOST/$DEPLOY_CONTEXT/
  only:
    variables:
      - $PROD_DEPLOY_HOST
      # GitLab 11.0+
      #- $PROD_DEPLOY_HOST =~ /^([a-z0-9-]+\.)*[a-z0-9-]+(:[0-9]+)?$/
    refs:
      - /^v[0-9]+/
      - /^[0-9]+\.[0-9]+$/
  before_script:
    - DEPLOY_HOST=$PROD_DEPLOY_HOST

tomcat_development:
  <<: *deploy
  environment:
    name: development/$DEV_DEPLOY_HOST
    url: https://$DEV_DEPLOY_HOST/api/
  only:
    variables:
      - $DEV_DEPLOY_HOST
      # GitLab 11.0+
      #- $DEV_DEPLOY_HOST =~ /^([a-z0-9-]+\.)*[a-z0-9-]+(:[0-9]+)?$/
  before_script:
    - DEPLOY_HOST=$DEV_DEPLOY_HOST
