trigger:
- dev

pool:
  vmImage: 'ubuntu-latest'

jobs:
- job: SetupNode
  displayName: 'Setup Node.js and npm'
  steps:
  - task: NodeTool@0
    inputs:
      versionSpec: '19.7.0'
      checkLatest: true

  - script: |
      echo "Node.js version:"
      node -v
      echo "npm version:"
      npm -v
      echo "Clearing npm cache"
      npm cache clean --force
      echo "Reinstalling npm"
      npm install -g npm@latest
    displayName: 'Verify Node.js and npm versions'

  - script: |
      echo "Checking Node.js and npm paths"
      which node
      which npm
      echo "PATH: $PATH"
    displayName: 'Check Node.js and npm Paths'

  - task: SSH@0
    inputs:
      sshEndpoint: 'Nucleus-SSH'
      runOptions: 'commands'
      commands: |
        echo "Checking SSH connectivity"
        whoami
        node -v
        npm -v
        echo "Cleaning old npm and Node.js installations"
        sudo apt-get remove --purge -y nodejs npm
        sudo apt-get autoremove -y
        sudo apt-get update
        echo "Reinstalling Node.js and npm"
        curl -fsSL https://deb.nodesource.com/setup_19.x | sudo -E bash -
        sudo apt-get install -y nodejs
        echo "Node.js and npm reinstalled"
        node -v
        npm -v
        echo "Navigating to project directory"
        cd /var/www/backend/graviti-mir-api.lexyslabs.com
        pwd
        sudo git -C /var/www/backend/graviti-mir-api.lexyslabs.com remote set-url origin https://dev.azure.com/lexystech/Project%20Nucleus/_git/Project-Nucleus-BE
        echo "git Seocnd checking"
        sudo git -C /var/www/backend/graviti-mir-api.lexyslabs.com pull https://4pnv6ffmikfcwvjdgvw4udrczde7qeel3kbbrtzdyew3ql4chngq:@dev.azure.com/lexystech/Project%20Nucleus/_git/Project-Nucleus-BE dev 2>/dev/null
        echo "git check"
        sudo npm install --prefix /var/www/backend/graviti-mir-api.lexyslabs.com --loglevel=error
        echo "Dependencies installed"
        sudo pm2 stop server
        sudo pm2 restart server
        echo "Pipeline execution completed"
        uptime
      failOnStdErr: true
