# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

trigger:
- main

variables:
  APP_NAME: "AutoWritter"
  ENVIRONMENT_NAME: "Testing (VM)"
  LINUX_SERVICE_CONNECTION: "VM_Deploy"
  LINUX_VM_HOST: "172.176.186.238"
  LINUX_VM_USER: "deployuser"

jobs:
- job: Build
  displayName: "Build Application"
  pool:
    name: 'Default' # Use the name of your agent pool

  steps:

#   - script: |
#       python3 -m venv venv
#       source venv/bin/activate
#       pip install -r requirements.txt
#     displayName: "Install Dependencies"

  - task: PublishPipelineArtifact@1
    inputs:
      targetPath: '$(Build.ArtifactStagingDirectory)'
      artifactName: 'drop'
      publishLocation: 'pipeline'

- job: Deploy
  displayName: "Deploy Application"
  # dependsOn: Build
  pool:
    name: 'Default' # Use the name of your agent pool

  steps:
  - task: DownloadPipelineArtifact@2
    inputs:
      artifact: 'drop'
      targetPath: '$(Pipeline.Workspace)'
      
  - script: |
      echo "Listing contents of $(Pipeline.Workspace)/s:"
      ls -R $(Pipeline.Workspace)/s
    displayName: "List Downloaded Artifact Contents"

  - task: CopyFilesOverSSH@0
    inputs:
      sshEndpoint: $(LINUX_SERVICE_CONNECTION)
      sourceFolder: '$(Pipeline.Workspace)/s'
      targetFolder: '/home/$(LINUX_VM_USER)/azure_apps/autowriter'
      cleanTargetFolder: true

  - task: SSH@0
    inputs:
      sshEndpoint: $(LINUX_SERVICE_CONNECTION)
      runOptions: 'inline'
      inline: |
        cd /home/$(LINUX_VM_USER)/azure_apps/autowriter

        # Find all PIDs of processes running on port 5000
        PIDS=$(lsof -t -i :5000)

        if [ ! -z "$PIDS" ]; then
            echo "Stopping existing processes running on port 5000 with PIDs: $PIDS"
            
            for PID in $PIDS; do
                kill -TERM $PID
                echo "Sent SIGTERM to process with PID: $PID"
                
                # Wait for the process to terminate
                sleep 5
                if kill -0 $PID 2>/dev/null; then
                    echo "Process $PID did not terminate, forcing kill"
                    kill -9 $PID
                fi
            done
            
            echo "All processes on port 5000 have been stopped."
        else
            echo "No processes found running on port 5000."
        fi

        python3 -m venv venv
        source venv/bin/activate
        python3 -m pip install -r requirements.txt
        export FLASK_APP=app.py
        export FLASK_ENV=production
        nohup flask run --host=0.0.0.0 --port=5000 > logs.out 2>&1 &
        disown
      failOnStdErr: true
      workingDirectory: '/home/$(LINUX_VM_USER)/azure_apps/autowriter'

  - script: |
      echo "Background process started, completing pipeline."
    displayName: 'Complete pipeline'
