pipeline {
  agent {
    label 'pi501.in.thelinuxpro.net'
  }

  stages {
    stage("verify tooling") {
      steps {
	sh '''
        docker version
	docker info
        docker compose version
        '''
      }
    }

    stage("Build Containers and push to registry") {
      steps {
	script {
	  sh 'docker compose build --push'
	}
      }
    }

    stage('Create contexts') {
      steps {
    	sh 'docker context ls | grep pi502 || docker context create pi502 --docker "host=ssh://pi502.in.thelinuxpro.net"'
      }
    }

    stage('Cleanup...') {
      steps {
	sh 'docker --context pi502 container stop syslog-ng || echo "syslog-ng container is not running."'
	sh 'docker --context pi502 container prune -f'
	sh 'docker --context pi502 volume prune -f'
	sh 'docker --context pi502 image prune -f'
      }
    }

    stage('Start container') {
      steps {
	script {
	  def status_s = sh(returnStatus: true, script: 'grep $(docker --context pi502 compose ps | tail -n1 | awk \'{ print $2 }\') docker-compose.yml')

	  if (status_s != 0) {
	    sh 'docker --context pi502 compose up -d'
	    sh 'docker --context pi502 compose ps'
	  } else {
	    echo 'skip'
	  }
	}
      }
    }

  }
}

