image: maven:latest

variables: 
  LANG: C.UTF-8
  LC_ALL: C.UTF-8
  PROJECT_ARTIFACT_ID: FIDENTIS-Analyst-app
  # FTP_* variables are defined in the CI condiguration of the gitlab.
  DEPLOYMENT_INFO_VERSION_FILE: VERSION.txt
  GIT_USER_EMAIL: oslejsek@fi.muni.cz
  GIT_USER_NAME: "Radek Oslejsek"
  GIT_CLONE_URL: "https://oauth2:1AbCDeF_g2HIJKLMNOPqr@gitlab.fi.muni.cz/grp-fidentis/analyst2.git"

stages:
    - tag_version
    - build
    - tests
    - publish

tag_version:
  stage: tag_version
  image: ubuntu:latest
  tags:
    - shared-fi
  before_script:
  # ssh config
  #- which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
  #- eval $(ssh-agent -s)
  #- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
  #- mkdir -p ~/.ssh
  #- chmod 700 ~/.ssh
  #- ssh -o 'StrictHostKeyChecking no' "$SSH_HOST_CHECKING_DOMAIN"
  # git config
  - apt-get install git -y
  - git config --global user.email "$GIT_USER_EMAIL"
  - git config --global user.name "$GIT_USER_NAME"
  - git remote set-url origin "$GIT_CLONE_URL"
  - git fetch
  - git checkout master
  script:
  - export VERSION=$(grep -oP '^([^\s]*)' $DEPLOYMENT_INFO_VERSION_FILE)
  - export TAG_MESSAGE=$(grep -oP '(?<=\s)[^\s].*' $DEPLOYMENT_INFO_VERSION_FILE)
  # update project in this project
#  - mvn versions:set -DnewVersion=$VERSION -DgenerateBackupPoms=false
#  - git commit -am "Update pom.xml version based on GitLab tag. Done by CI."
  # update change log
#  - LAST_TAG=$(git tag | head -1)
#  - git log  --pretty=format:'%h -- %s' $LAST_TAG..HEAD --graph > CHANGELOG.md
#  - git add CHANGELOG.md
#  - git commit -m "CHANGELOG.md file updated with commits between the current and previous tag. Done by CI."
  # create new tag
#  - git tag -a v$VERSION -m "$TAG_MESSAGE"
#  - git config --global push.followTags true
#  - git push
#  rules:
#  - if: '$CI_COMMIT_BRANCH == "master"'
#    changes:
#      - VERSION.txt
  artifacts:
    paths:
    - ./pom.xml
    - ./*/pom.xml
    expire_in: 1 hour
    when: on_success

build:
  stage: build
  script:
    - mvn clean install -B -DskipTests -Dcheckstyle.fail=false
  tags:
    - shared-fi
  rules:
    - if: '$CI_COMMIT_BRANCH'
  artifacts:
    paths:
    - application/target/$PROJECT_ARTIFACT_ID-*.zip
    expire_in: 1 hour
    when: on_success

tests:
  stage: tests
  script:
    - mvn test -B -Dcheckstyle.fail=false
  tags:
    - shared-fi
  rules:
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes:
        - VERSION.txt
      when: never
    - if: '$CI_COMMIT_BRANCH'

publish:
  stage: publish
  image: ubuntu:latest
  script:
    - apt-get update -qq && apt-get install -y -qq lftp
    - lftp -c "set ftp:ssl-allow no; open -u $FTP_USERNAME,$FTP_PASSWORD $FTP_HOST; mirror -Rnev $CI_PROJECT_DIR/application/target ./$FTP_TARGET_DIR --ignore-time --parallel=10 --exclude-glob .git* --exclude .git/"
    #- echo $FTP_HOST $FTP_USERNAME $FTP_PASSWORD $FTP_TARGET_DIR $CI_PROJECT_DIR
  tags:
    - shared-fi
  only:
    - master
