---

## VARIABLES
variables:
  REPOSITORY:
    value: ""
    description: "ОБЯЗАТЕЛЬНАЯ ПЕРЕМЕННАЯ: указываем имя репозитория с плейбуком"
  PLAYBOOK:
    value: ""
    description: "неОБЯЗАТЕЛЬНАЯ ПЕРЕМЕННАЯ: указываем имя (и путь до) плейбука"
  PARAMETERS:
    value: ""
    description: "неОБЯЗАТЕЛЬНАЯ ПЕРЕМЕННАЯ: Передаём нужные параметры"

##########################################################################################################

## PIPELINE DEFINITION
stages:
  - check
  - deploy

##########################################################################################################

### COMMON SECTION
.common:
  image: $ANSIBLE_IMAGE
  variables:
    GIT_DEPTH: 1
    ANSIBLE_FORCE_COLOR: "True"
    ANSIBLE_HOST_KEY_CHECKING: "False"
  before_script:
    - eval $(ssh-agent -s); echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - mkdir -p ~/.ssh && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    - chmod -R o-w ../

##########################################################################################################

### CHECK SECTION
check:
  extends: .common
  stage: check
  except:
    refs:
      - master
  script:
    - echo "Checking inventory"
    - ansible-inventory -i inventory.yml --graph
    - ansible -i inventory.yml -m ping -u ${USERNAME:-maintenance} all:\!ungrouped:\!workstations || true

##########################################################################################################

### DEPLOY SECTION
deploy:
  extends: .common
  stage: deploy
  only:
    refs:
      - master
    variables:
      - $REPOSITORY =~ /^\S+$/
  script:
    - echo "Deploying configuration [${REPOSITORY}] with parameters [${PARAMETERS}] and playbook [${PLAYBOOK:-run.yml}]"
    - export INVENTORY_DIRECTORY="`pwd`"
    - export ANSIBLE_CONFIG="${INVENTORY_DIRECTORY}/ansible.cfg"
    - git config --global credential.helper store && echo "https://${GIT_LOGIN}:${GIT_PASSWORD}@$(echo ${REPOSITORY} | sed -r 's#([^/])/[^/].*#\1#' | sed -e 's|https://||g')" > ~/.git-credentials
    - mkdir -p /tmp/checkout && git clone "${REPOSITORY}" /tmp/checkout && cd /tmp/checkout
    - test -s ansible.cfg && export ANSIBLE_CONFIG="`pwd`/ansible.cfg" || true
    - test -s requirements.yml && ansible-galaxy install -r requirements.yml || true
    - test -s setup.yml && ansible-playbook ${PARAMETERS} -u ${USERNAME:-maintenance} -i "${INVENTORY_DIRECTORY}/inventory.yml" setup.yml || true
    - test -s "${PLAYBOOK:-run.yml}" && ansible-playbook ${PARAMETERS} -u ${USERNAME:-maintenance} -i "${INVENTORY_DIRECTORY}/inventory.yml" "${PLAYBOOK:-run.yml}" || ( echo "Can't use playbook [${PLAYBOOK:-run.yml}]!" && exit 1 )
