image: node:8
tags:
  - docker

stages:
  - preview
  - deployment

# env vars:
# - PREVIEW_SSH_KEY
preview:
  stage: preview
  variables:
    HTML_DIR: "/var/www/html/preview.ok1kvk.cz"
    SSH_HOST: "preview-ok1kvk-cz@alfa.ok1kvk.cz"
  environment: 
    name: preview/$CI_BUILD_REF_NAME
    url: https://preview.ok1kvk.cz/$CI_BUILD_REF_NAME
    on_stop: stop_preview
  except:
    - master
  script:
    - node --version
    - rm -rf build
    - if [ -d generator ] ; then cd generator; git pull; cd ..; else git clone https://git.ok1kvk.cz/ok1kvk.cz/generator.git; fi
    - mkdir -p fake_static
    - cd generator/; npm install; cd ..
    - node generator/index.js --baseurl /$CI_BUILD_REF_NAME --contentdir . --staticdir fake_static --themedir generator/theme --builddir build --noserver
    - echo "$PREVIEW_SSH_KEY" > sshkey
    - chmod 600 sshkey
    - rsync -e 'ssh -i sshkey' -rc --delete build/ $SSH_HOST:$HTML_DIR/$CI_BUILD_REF_NAME/
    - ssh -i sshkey $SSH_HOST git -C $HTML_DIR/static/static/ pull
    - ssh -i sshkey $SSH_HOST cp -asf $HTML_DIR/static/static/articles/. $HTML_DIR/$CI_BUILD_REF_NAME/clanek/
    - ssh -i sshkey $SSH_HOST ln -sf $HTML_DIR/static/static/images/ $HTML_DIR/$CI_BUILD_REF_NAME/
    - rm sshkey

stop_preview:
  stage: preview
  variables:
    HTML_DIR: "/var/www/html/preview.ok1kvk.cz"
    SSH_HOST: "preview-ok1kvk-cz@alfa.ok1kvk.cz"
  script:
    - echo "$PREVIEW_SSH_KEY" > sshkey
    - chmod 600 sshkey
    - ssh -i sshkey $SSH_HOST "rm -rf $HTML_DIR/$CI_BUILD_REF_NAME/"
    - rm sshkey
  when: manual
  environment:
    name: preview/$CI_BUILD_REF_NAME
    action: stop
  except:
    - master
    
# Needs following env vars:
# - LFTP_PASSWORD
# - DEPLOY_SSH_KEY
deploy:
  stage: deployment
  environment: deployment
  variables:
    HTML_DIR: "/html/www"
    SSH_HOST: "uploader@cloud.ok1kvk.cz"
  only:
    - master
  script:
    - node --version
    - rm -rf build
    - if [ -d generator ] ; then cd generator; git pull; cd ..; else git clone https://git.ok1kvk.cz/ok1kvk.cz/generator.git; fi
    - if [ -d static    ] ; then cd static;    git pull; cd ..; else git clone https://git.ok1kvk.cz/ok1kvk.cz/static.git;    fi
    - cd generator/; npm install; cd ..
    - node generator/index.js --contentdir . --staticdir static --themedir generator/theme --builddir build --noserver
    - echo "$DEPLOY_SSH_KEY" > sshkey
    - chmod 600 sshkey
    - rsync -e 'ssh -i sshkey' -rc --delete build/ $SSH_HOST:$HTML_DIR/
    - rm sshkey

cache:
  paths:
    - generator/
    - static/

