image: docker:20.10.5

stages:
  - build
  - push
  - deploy
.before_script
  before_script:
    - echo -n $CI_REGISTRY_TOKEN | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY

build:
  extends: .before_script
  stage: build
  tags:
    - docker
  script:
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

# Tag the "master" branch as "latest"
push latest:
  extends: .before_script
  stage: push
  tags:
    - docker
  script:
    - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:latest
    - docker push $CI_REGISTRY_IMAGE:latest
  only:
    - master

# Docker tag any Git tag
push tag:
  extends: .before_script
  stage: push
  tags:
    - docker
  only:
    - tags
  script:
    - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG

# Docker Deploy
# deploy:
#   extends: .before_script
#   stage: deploy
#   tags:
#     - docker
#   environment:
#     name: Production
#     url: "$LIVE_SERVER_FQDN"
#   before_script:
#   - 'command -v ssh-agent >/dev/null || ( 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
#   - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" >> ~/.ssh/config'
#   script:
#     - echo 'sed 's/"$CI_REGISTRY_IMAGE".*/"$CI_REGISTRY_IMAGE":"$CI_COMMIT_SHA"''
#     - ssh -J "$PROD_SERVER_USER"@"$LIVE_SERVER_FQDN" "$PROD_SERVER_USER"@"$PROD_SERVER_LOCAL_HOST_NAME" "cd simple-blog-api && sed -i 's/simple-blog-api.*/simple-blog-api:"$CI_COMMIT_SHA"\x27/' docker-compose.yml && docker-compose up -d --remove-orphans --force-recreate"

deploy:
  stage: deploy
  image:
    name: alpine/helm:latest
    entrypoint: [""]
  script:
    - helm upgrade
      --install
      --wait
      --set image.tag=${CI_COMMIT_SHA}
      simple-blog-api-${CI_COMMIT_REF_SLUG}
      devops/simple-blog-api
  environment:
    name: production
