name: deploy

on:
  push:
    branches:
      - main

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

      - name: Cache
        uses: actions/cache@v4
        with:
          path: |
            dist/
            node_modules/
          key: ${{ runner.os }}-${{ hashFiles('package-lock.json') }}

      - name: Install dependencies
        run: npm i

      - name: Build website
        env:
          BASE_PATH: ${{ vars.BASE_PATH }}
        run: npm run build

      - name: Deploy
        env:
          HOST: ${{ vars.SSH_HOST}}
          USER: ${{ vars.SSH_USER }}
          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/server; mkdir -p /opt/website/server"
          scp -r -o StrictHostKeyChecking=no $(ls -d -1 dist/*) $(ls package*) $USER@$HOST:/opt/website/server
          ssh -o StrictHostKeyChecking=no $USER@$HOST "cd /opt/website/server; npm i --omit=dev; systemctl restart website.service"
