stages:
  - build
  - test
  - deploy
  - publish

.gms_client:
  tags:
    - docker
  rules:
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes:
        - gms-client/gms-client/*

build_gms_client:
  extends: .gms_client
  stage: build
  script:
    - cd gms-client/gms-client
    - mvn clean package -DskipTests -DfinalName=gms-client
  artifacts:
    paths:
      - gms-client/gms-client/target/gms-client.jar
      - gms-client/gms-client/pom.xml
    expire_in: 7 days

test_gms_client:
  extends: .gms_client
  stage: test
  script:
    - cd gms-client/gms-client
    - mvn clean test
    
test_gms:
  stage: test
  tags:
    - docker
  image: git.ia2.inaf.it:5050/ia2/ia2-devops/maven-otj-pg-embedded
  script:
    - cd gms
    - mvn clean test
    - awk -F"," '{ instructions += $4 + $5; covered += $5 } END { print "coverage=" 100*covered/instructions }' target/site/jacoco/jacoco.csv
  coverage: '/coverage=\d+\.\d+/'
  rules:
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes:
        - gms/*

deploy_gms_client:
  extends: .gms_client
  stage: deploy
  script:
    - mvn deploy:deploy-file
        -Dfile=gms-client/gms-client/target/gms-client.jar
        -DrepositoryId=ia2.snapshots
        -DpomFile=gms-client/gms-client/pom.xml
        -Durl=${IA2_MVN_REPO_SNAPSHOTS}

deploy_gms_lib:
  stage: deploy
  tags:
    - docker
  script:
    - cd gms
    - mvn clean package -DskipTests
    - version=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)
    - mvn deploy:deploy-file
        -Dfile=target/gms-lib.jar
        -DartifactId=gms
        -DgroupId=it.inaf.ia2
        -Dclassifier=lib
        -DrepositoryId=ia2.snapshots
        -Dversion=$version
        -Durl=${IA2_MVN_REPO_SNAPSHOTS}
        -DpomFile=pom.xml
  rules:
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes:
        - gms/*

dockerize_db:
  stage: deploy
  tags:
    - shell
  script:
    - docker login -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}" "${CI_REGISTRY}"
    - docker build -t "${CI_REGISTRY_IMAGE}/database" -f database/Dockerfile .
    - docker push "${CI_REGISTRY_IMAGE}/database"
  rules:
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes:
        - database/*
        - gms/src/main/resources/sql/*

dockerize_gms:
  stage: deploy
  tags:
    - shell
  script:
    - docker login -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}" "${CI_REGISTRY}"
    - docker build -t "${CI_REGISTRY_IMAGE}" -f gms/Dockerfile .
    - docker push "${CI_REGISTRY_IMAGE}"
  rules:
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes:
        - gms/*
        - gms-ui/*

upload_jar:
  stage: publish
  tags:
    - shell
  only:
    - master
  script:
    # extract jar from Docker image
    - docker run --rm --entrypoint cat "${CI_REGISTRY_IMAGE}" /gms.jar > gms.jar
    - 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file gms.jar "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/gms/latest/gms.jar"'
