# Official framework image. Look for the different tagged releases at:
# https://hub.docker.com/r/library/node/tags/
image: node:10-stretch

# Only needed when using a docker container to run your tests in.
# Check out: http://docs.gitlab.com/ce/ci/docker/using_docker_images.html#what-is-a-service
services:
   - postgres

# This folder is cached between builds
cache:
  paths:
  - node_modules/
  - ldap_connexion_config.json

stages:
  - install
  - test
  - build
  - deploy

### Jobs ###

# Install dependencies, compile the bundle.js,
# make migrations on and seed the db
install-dependencies:
  stage: install
  script:
    - npm ci
  artifacts:
    paths:
      - node_modules/

build:
  stage: build
  before_script:
    - export NODE_ENV=staging
    - echo $LDAP_CONN_CONFIG > ldap_connexion_config.json
  script: npm run build
  artifacts:
    paths:
      - build/

deploy-staging:
  stage: deploy
  only:
    - stable
  before_script:
    - export NODE_ENV=staging
    - eval $(ssh-agent -s)
    - ssh-add <(echo "$STAGING_PRIVATE_KEY")
    - mkdir -p ~/.ssh
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
  script:
    - ssh -p22 sigma-dev@129.104.201.10 "mkdir -p /opt/sigma-back-dev"
    - ssh -p22 sigma-dev@129.104.201.10 "rm -rf /opt/sigma-back-dev/build"
    - ssh -p22 sigma-dev@129.104.201.10 "rm -rf /opt/sigma-back-dev/assets"
    - scp -p22 -r build/ sigma-dev@129.104.201.10:/opt/sigma-back-dev/build
    - scp -p22 -r assets/ sigma-dev@129.104.201.10:/opt/sigma-back-dev/assets
    - scp -p22 -r db/ sigma-dev@129.104.201.10:/opt/sigma-back-dev/db
    - scp -p22 knexfile.js sigma-dev@129.104.201.10:/opt/sigma-back-dev/knexfile.js
    - ssh -p22 sigma-dev@129.104.201.10 "cd /opt/sigma-back-dev && knex migrate:latest && knex seed:run"
    - scp -p22 package.json "package-lock.json" ldap_config.json ldap_connexion_config.json sigma-back-dev.service sigma-dev@129.104.201.10:/opt/sigma-back-dev/
  environment:
    name: staging
    url: http://129.104.201.10:3000
