name: delpoy

on:
  push:

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Install dependencies
        run: npm i

      - name: Build website
        run: npm run build

      - name: Deploy
        env:
          HOST: 10.20.6.7
          USER: root
          SSH_KEY: ${{ secrets.SSH_KEY }}
        run: |
          mkdir -p "$HOME/.ssh" && touch "$HOME/.ssh/known_hosts"
          echo "$SSH_KEY" > "$HOME/.ssh/deploy_key"
          chmod 700 "$HOME/.ssh" && chmod 600 "$HOME/.ssh/known_hosts" && chmod 600 "$HOME/.ssh/deploy_key"
          eval $(ssh-agent)
          ssh-add "$HOME/.ssh/deploy_key"
          ssh-keyscan -t rsa "$HOST" >> "$HOME/.ssh/known_hosts"

          ssh -o StrictHostKeyChecking=no $USER@$HOST "rm -r /opt/website; mkdir -p /opt/website"
          scp -r -o StrictHostKeyChecking=no $(ls -d -1 build/*) $(ls package*) $USER@$HOST:/opt/website
          ssh -o StrictHostKeyChecking=no $USER@$HOST "cd /opt/website; npm i --omit=dev; systemctl restart website"
