name: CI deploy production
on:
  push:
    branches: ["production"]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v2
        with:
          node-version: "16"
      - name: Setup Host SSH
        run: |
          mkdir -p ~/.ssh
          echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
          chmod 600 ~/.ssh/known_hosts
        shell: bash
        env:
          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
          SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
      - name: Install pm2
        run: npm install pm2 --location=global
        shell: bash
      - name: Deploy using pm2
        run: pm2 deploy ecosystem.config.js production
        env:
          # Deploy environment variables 
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          SSH_USERNAME: ${{ secrets.SSH_USERNAME }}
          SSH_HOST: ${{ secrets.SSH_HOST }}
          DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
          # App environment variables
          APP_NAME: ${{ secrets.APP_NAME }}
          SITE_NAME: ${{ secrets.SITE_NAME }}
          PORT: ${{ secrets.PORT }}
          DISCORD_JOIN_WEBHOOK_URL: ${{ secrets.DISCORD_JOIN_WEBHOOK_URL }}
        shell: bash
