trigger:
  branches:
    include:
      - develop

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: SSH@0
  inputs:
    sshEndpoint: 'ResolvedDevMachine'  # Use the name of your SSH service connection
    runOptions: 'inline'
    inline: |
      cd /var/www/api/resolved/resolved-node-api 
      pwd  # Print the current working directory for debugging
      eval $(ssh-agent) 2>&1
      ssh-add ~/.ssh/resolved 2>&1

      # Check for unstaged changes
      UNSTAGED_FILES=$(git diff --name-only)
      echo "Unstaged files: $UNSTAGED_FILES"

      if [ -n "$UNSTAGED_FILES" ]; then
        git stash save "Stashing unstaged changes"
      fi

      git pull origin develop 2>&1

      # Load nvm
      export NVM_DIR="$HOME/.nvm"
      [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

      # Use the correct Node.js version
      nvm use v18.12.1 2>&1

      LATEST_COMMIT=$(git rev-parse HEAD)

      # Check for changes in package.json
      CHANGED_FILES=$(git diff --name-only $LATEST_COMMIT^..$LATEST_COMMIT)
      echo "Changed files: $CHANGED_FILES"

      if echo "$CHANGED_FILES" | grep -q "package.json"; then
      	npm install
        fi
      /root/.nvm/versions/node/v18.12.1/bin/npx prisma generate
      /root/.nvm/versions/node/v18.12.1/bin/npx prisma migrate dev --name "$(date +'%Y%m%d%H%M%S')" 2>&1

      # Restart application using pm2
      /root/.nvm/versions/node/v18.12.1/bin/pm2 restart 2 2>&1

  displayName: 'Deploy to Ubuntu Server'
  