pipelines:
  custom:
    react-pipeline:
      - step:
          name: "React Pipeline"
          oidc:
            enable: true
          runs-on:
            - self.hosted
            - linux.shell
          script:
            # Step 1: Zip project files
            - zip -r /home/ubuntu/exampur.zip .

            # Step 2: Create the build directory and extract files
            - sudo mkdir -p /home/ubuntu/exampur
            - sudo unzip -o /home/ubuntu/exampur.zip -d /home/ubuntu/exampur || { echo "Unzip failed"; exit 1; }
            - sudo rm /home/ubuntu/exampur.zip

            # Step 3: Move to the build directory
            - cd /home/ubuntu/exampur

            # Step 4: Install dependencies
            - sudo npm install --force || { echo "npm install failed"; exit 1; }

            # Step 5: Build the project
            - sudo npm run build || { echo "npm run build failed"; exit 1; }

            # Step 6: Ensure .ssh directory exists
            - mkdir -p /home/ubuntu/.ssh

            # Step 7: Set correct permissions for the SSH key
            - chmod 600 /home/ubuntu/react.pem

            # Step 8: Set SSH config to avoid SSH key checking
            - echo "Host *" > /home/ubuntu/.ssh/config
            - echo "  StrictHostKeyChecking no" >> /home/ubuntu/.ssh/config
            - chmod 600 /home/ubuntu/.ssh/config

            # Step 9: Zip the project files
            - sudo zip -r /home/ubuntu/exampur.zip /home/ubuntu/exampur/

            # Step 10: Transfer the zip file to the EC2 server (Default Port 22)
            - sudo scp -i /home/ubuntu/react.pem /home/ubuntu/exampur.zip ubuntu@172.31.7.218:/home/ubuntu/ || { echo "SCP transfer failed"; exit 1; }

            # Step 11: SSH into EC2, unzip the file, and restart PM2
            - |
               ssh -i /home/ubuntu/react.pem ubuntu@172.31.7.218 << 'EOF'
                echo "Unzipping project files..."
                sudo unzip -o /home/ubuntu/exampur.zip -d /var/www/html/
                sudo pm2 restart exampur_app || { echo "PM2 restart failed"; exit 1; }
                echo "Files have been updated!"
                EOF
