default:
  image: witel/rms:1.0


stages:
  - test
  - lint
  - deploy

variables:
  TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest
  TAG_COMMIT: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:$CI_COMMIT_SHORT_SHA
  TARGET_BRANCH_NAME: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
  GIT_STRATEGY: fetch
  GIT_DEPTH: 10
  GIT_HTTP_LOW_SPEED_LIMIT: 1000  # Bytes per second
  GIT_HTTP_LOW_SPEED_TIME: 30
  MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD

# https://docs.gitlab.com/ee/ci/yaml/index.html#cache
cache:
  paths:
    - vendor/

services:
  - name: mysql:latest
    alias: mysql

before_script:
  - apk update
  - command=$(ls && pwd)
  - echo "'$command'"
  - cp .env.example .env
  - composer install
  - php artisan key:generate
  - apk add --no-cache ca-certificates
  - update-ca-certificates
  - git fetch


test:
  stage: test
  script:
    - php artisan config:clear
    - cp .env.example .env.testing
    - sed -i "s/DB_HOST=127.0.0.1/DB_HOST=mysql/" .env.testing
    - sed -i "s/DB_DATABASE=/DB_DATABASE=$MYSQL_DATABASE/" .env.testing
    - sed -i "s/DB_USERNAME=/DB_USERNAME=$MYSQL_USERNAME/" .env.testing
    - sed -i "s/DB_PASSWORD=/DB_PASSWORD=$MYSQL_ROOT_PASSWORD/" .env.testing
    - cat .env.testing
    - php artisan key:generate --env=testing
    - php artisan migrate --path=/database/old_migrations/ --path=database/migrations --env=testing --force
    - php artisan test
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      when: always

.lint:
  stage: lint
  script:
    - log=$(git log && git log -p)
    - echo "'$log'"
    - echo "'$CI_COMMIT_SHA'"
    - CHANGED_FILES=$( git diff-tree --name-only -r origin/$TARGET_BRANCH_NAME -r $CI_COMMIT_SHA)
    - echo $CHANGED_FILES
    - composer require --dev squizlabs/php_codesniffer
    - vendor/bin/phpcs --standard=PSR12 $CHANGED_FILES

  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      when: always
      allow_failure: true

#deploy:
#  stage: deploy
#  script:
#    - apt-get update && add --no-cache openssh-client
#    - chmod og-rwx $ID_RSA
#    - ssh -i $ID_RSA -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "
#      echo -e '$SHECAN_DNS' | sudo tee /etc/resolv.conf &&
#      dns=\$(cat /etc/resolv.conf) &&
#      echo \"\$dns\" &&
#      cd $PROJECT_PATH &&
#      git checkout $TARGET_BRANCH_NAME &&
#      ssh -T git@gitlab.com &&
#      git pull ssh-origin $TARGET_BRANCH_NAME &&
#      echo -e '$DEFAULT_DNS' | sudo tee /etc/resolv.conf"
#  resource_group: develop_deploy
#  rules:
#    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_REF_NAME == "develop"'

