image: rust:latest

variables:
  CARGO_TARGET: x86_64-unknown-linux-musl

before_script:
  - rustup target add $CARGO_TARGET
  - apt-get update -qq && apt-get install -y -qq sshpass musl musl-tools sqlite3 curl gnupg && curl -sL https://deb.nodesource.com/setup_16.x | bash - && apt-get install -y nodejs
  - ./test_db.sh

build:
  stage: build
  script:
    - cargo build --release --target $CARGO_TARGET
    - cd frontend && npm install && npm run build
      #    - strip target/$CARGO_TARGET/release/rot
  artifacts:
    paths:
      - target/$CARGO_TARGET/release/rot
      - static
    expire_in: 1 week

test:
  stage: test 
  image: rust:latest
  script:
    - cargo test --verbose

deploy-staging:
  stage: deploy
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan -H $SSH_HOST > ~/.ssh/known_hosts
  script:
    - scp target/$CARGO_TARGET/release/rot $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/rot-updating
    - scp -r static $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/
    - scp -r templates $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/
    - scp -r svelte $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/
    - ssh $SSH_USER@$SSH_HOST 'sudo systemctl stop rotstaging'
    - ssh $SSH_USER@$SSH_HOST 'rm /home/k004373/rowing-staging/db.sqlite && cp /home/k004373/rowing/db.sqlite /home/k004373/rowing-staging/db.sqlite && mkdir -p /home/k004373/rowing-staging/svelte/build'
    - ssh $SSH_USER@$SSH_HOST 'mv  /home/k004373/rowing-staging/rot-updating /home/k004373/rowing-staging/rot'
    - ssh $SSH_USER@$SSH_HOST 'sudo systemctl start rotstaging'
  only:
    - staging 

deploy-main:
  stage: deploy
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan -H $SSH_HOST > ~/.ssh/known_hosts
  script:
    - scp target/$CARGO_TARGET/release/rot $SSH_USER@$SSH_HOST:/home/k004373/rowing/rot-updating
    - scp -r static $SSH_USER@$SSH_HOST:/home/k004373/rowing/
    - scp -r templates $SSH_USER@$SSH_HOST:/home/k004373/rowing/
    - scp -r svelte $SSH_USER@$SSH_HOST:/home/k004373/rowing/
    - ssh $SSH_USER@$SSH_HOST 'mkdir -p /home/k004373/rowing/svelte/build'
    - ssh $SSH_USER@$SSH_HOST 'sudo systemctl stop rot'
    - ssh $SSH_USER@$SSH_HOST 'mv  /home/k004373/rowing/rot-updating /home/k004373/rowing/rot'
    - ssh $SSH_USER@$SSH_HOST 'sudo systemctl start rot'
  only:
    - main