name: Deploy to EC2

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    env:
      EC2_HOST: 18.223.231.19
      EC2_USERNAME: ubuntu
      EC2_APP_PATH: /var/www/OTM/injectionProject
      SLACK_WEBHOOK_URL: https://hooks.slack.com/services/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
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: |
          pip install -r requirements.txt
      
      - name: Get commit message
        id: commit
        run: |
          echo "message=$(git log -1 --pretty=%B | head -n 1)" >> $GITHUB_OUTPUT
      
      - name: Notify Slack - Build Started
        env:
          BUILD_STATUS: started
          COMMIT_MESSAGE: ${{ steps.commit.outputs.message }}
        run: python slack_notify.py
        continue-on-error: true
      
      - name: Deploy via Git Pull
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ env.EC2_HOST }}
          username: ${{ env.EC2_USERNAME }}
          key: ${{ secrets.SPARK_STAGING }}
          port: 22
          script: |
            cd ${{ env.EC2_APP_PATH }}
            sudo git pull origin main

      - name: Restart app on EC2
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ env.EC2_HOST }}
          username: ${{ env.EC2_USERNAME }}
          key: ${{ secrets.SPARK_STAGING }}
          port: 22
          script: |
            cd ${{ env.EC2_APP_PATH }}
            sudo npm i
            sudo pm2 restart 5
      
      - name: Notify Slack - Build Success
        if: success()
        env:
          BUILD_STATUS: success
          COMMIT_MESSAGE: ${{ steps.commit.outputs.message }}
        run: python slack_notify.py
        continue-on-error: true
      
      - name: Notify Slack - Build Failed
        if: failure()
        env:
          BUILD_STATUS: failed
          COMMIT_MESSAGE: ${{ steps.commit.outputs.message }}
        run: python slack_notify.py
        continue-on-error: true
