stages:
  - prepare
  - build

prepare_node:
  stage: prepare
  image: node:10
  before_script:
    - npm install
  script: 
    - npm run prod
  artifacts:
    paths:
      - node_modules
      - public/css/all.css
  cache:
    # Cache per Branch
    key: "node-$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
    paths:
      - node_modules
  only:
    - branches
    - tags
    
prepare_composer:
  stage: prepare
  image: composer/composer:latest
  script:
    - composer install
  artifacts:
    paths:
      - vendor
  cache:
    key: "composer-$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
    paths:
      - vendor

build:
  stage: build
  image: "registry.gitlab.com/gitlab-org/cluster-integration/auto-build-image/master:stable"
  variables:
    DOCKER_TLS_CERTDIR: ""
  services:
    - docker:stable-dind
  script:
    - |
      if [[ -z "$CI_COMMIT_TAG" ]]; then
        export CI_APPLICATION_REPOSITORY=${CI_APPLICATION_REPOSITORY:-$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG}
        export CI_APPLICATION_TAG=${CI_APPLICATION_TAG:-$CI_COMMIT_SHA}
      else
        export CI_APPLICATION_REPOSITORY=${CI_APPLICATION_REPOSITORY:-$CI_REGISTRY_IMAGE}
        export CI_APPLICATION_TAG=${CI_APPLICATION_TAG:-$CI_COMMIT_TAG}
      fi
    - |
      if ! docker info &>/dev/null; then
        export DOCKER_HOST='tcp://docker-dind.gitlab:2375'
      fi
    - |
      if [[ -n "$CI_REGISTRY" && -n "$CI_REGISTRY_USER" ]]; then
        echo "Logging to GitLab Container Registry with CI credentials..."
        docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
      fi
    - |
      if [[ -f Dockerfile ]]; then
        echo "Building Dockerfile-based application..."
      else
        echo "Building Heroku-based application using gliderlabs/herokuish docker image..."
        cp /build/Dockerfile Dockerfile
      fi
    # shellcheck disable=SC2154 # missing variable warning for the lowercase variables
    # shellcheck disable=SC2086 # double quoting for globbing warning for $AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS
    - docker pull $CI_APPLICATION_REPOSITORY:latest
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest --build-arg BUILDPACK_URL="$BUILDPACK_URL" --build-arg HTTP_PROXY="$HTTP_PROXY" --build-arg http_proxy="$http_proxy" --build-arg HTTPS_PROXY="$HTTPS_PROXY" --build-arg https_proxy="$https_proxy" --build-arg FTP_PROXY="$FTP_PROXY" --build-arg ftp_proxy="$ftp_proxy" --build-arg NO_PROXY="$NO_PROXY" --build-arg no_proxy="$no_proxy" $AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS --tag "$CI_APPLICATION_REPOSITORY:$CI_APPLICATION_TAG" --tag "$CI_APPLICATION_REPOSITORY:latest" .
    - docker push "$CI_APPLICATION_REPOSITORY:latest"
    - docker push "$CI_APPLICATION_REPOSITORY:$CI_APPLICATION_TAG"
  only:
    - branches
    - tags
