variables:
  LOCAL_DIR: public

stages: 
 - build
 - test_deployment
 - production_deployment

.sftp: &sftp_template
  image: ${CI_REGISTRY_IMAGE}/ubuntu_sftp
  tags:
    - wasenweiler.sit-servers.net
  script:
    - mkdir -p ~/.ssh
    - echo "${SFTP_KEY}" > ~/.ssh/id_rsa
    - echo "${SFTP_HOSTCERT}" > ~/.ssh/known_hosts
    - chmod 600 ~/.ssh/*
    - mv ${LOCAL_DIR} ${REMOTE_DIR}
    - >
      if [ ! -z "${PREVIEW}" ]; then
      find ${REMOTE_DIR} -type f -print0 | xargs -0 sed -i 's;</body>;<script src="/.version.js"></script></body>;g';
      echo "document.body.innerHTML += '<div style=\"position:fixed; bottom:60px; right:-60px; background-color:#d34; padding: 6px 100px; transform: rotate(-45deg); border-top: 1px solid #400; border-bottom: 1px solid #400;\"><a href=\"${CI_PROJECT_URL}/commit/${CI_COMMIT_SHA}\" style=\"color:#fff;\">Preview: ${CI_COMMIT_SHA:0:8}</a></div>';" > ${REMOTE_DIR}/.version.js;
      fi;

    - sftp ${SFTP_USERNAME}@${SFTP_HOST} <<< "put -r ${REMOTE_DIR}"


brunch_build:
  stage: build
  image: node
  before_script:
    - npm i -g brunch
  script:
    - npm i
    - brunch b --production
  artifacts:
    paths:
      - public/*
    expire_in: 3 days

test_deploy: 
  stage: test_deployment
  dependencies:
    - brunch_build
  variables:
    SFTP_USERNAME: ${TEST_USERNAME}
    SFTP_KEY: ${TEST_KEY}
    SFTP_HOST: ${TEST_HOST}
    SFTP_HOSTCERT: ${TEST_HOSTCERT}
    REMOTE_DIR: ${TEST_DIR}
    GIT_STRATEGY: none
    PREVIEW: "true"

  environment:
    name: Preview
    url: https://longroute.preview.sauerburger.com/

  <<: *sftp_template

production_deploy: 
  stage: production_deployment
  dependencies:
    - brunch_build
  variables:
    SFTP_USERNAME: ${PRODUCTION_USERNAME}
    SFTP_KEY: ${PRODUCTION_KEY}
    SFTP_HOST: ${PRODUCTION_HOST}
    SFTP_HOSTCERT: ${PRODUCTION_HOSTCERT}
    REMOTE_DIR: ${PRODUCTION_DIR}
    GIT_STRATEGY: none

  only:
    - master
  when: manual

  environment:
    name: Production
    url: https://longroute.sauerburger.com/

  <<: *sftp_template

