name: Deploy to RCAccess Frontend Server

on:
  push:
    branches: ['master','main']

  workflow_dispatch:
    

jobs:
  
  build:

    runs-on: self-hosted
    name: Build and Deploy

    steps:
      - name: Checking out latest code
        uses: actions/checkout@v3

      - name: Get the short commit hash
        id: git-info
        run: echo ::set-output name=commit_hash::$(git rev-parse --short HEAD)

      - name: Make Zip
        run: zip -r ${{ steps.git-info.outputs.commit_hash }}.zip .

      - name: Copy to www
        run: cp ${{ steps.git-info.outputs.commit_hash }}.zip /var/www/html/${{ steps.git-info.outputs.commit_hash }}.zip
     
      - name: executing remote ssh commands using password
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}

          script: |
            export NVM_DIR=~/.nvm
            source ~/.nvm/nvm.sh
            # nvm use 22
            
            pm2 delete rcaccess || true
            cd /var/www/html/rcaccess
            rm -rf *
            # rm -rf .*
            # cp ../${{ steps.git-info.outputs.commit_hash }}.zip ./${{ steps.git-info.outputs.commit_hash }}.zip
            wget http://143.110.234.95/${{ steps.git-info.outputs.commit_hash }}.zip
            unzip ${{ steps.git-info.outputs.commit_hash }}.zip
            npm install --force
            #npm run build
            env NEXT_PRIVATE_WORKER_COUNT=2 NEXT_SKIP_TYPE_CHECK=1 NODE_OPTIONS="--max-old-space-size=2048" npm run build
            PORT=7788 pm2 start npm --name "rcaccess" -- start

      - name: Cleanup
        run: |
          rm ${{ steps.git-info.outputs.commit_hash }}.zip 
        #   rm /var/www/html/inhouse/${{ steps.git-info.outputs.commit_hash }}.zip
