pipeline {

    agent none

    options {
        buildDiscarder logRotator(
                    daysToKeepStr: '15',
                    numToKeepStr: '10'
            )
    }
    parameters {
        string(name: 'VERSION', defaultValue: '', description: 'Version')
        string(name: 'BRANCH',  defaultValue: 'main', description: '[Optional] Branch name to clone. Default (main) ')
        string(name: 'DOCKER',  defaultValue: '', description: 'http url of docker tar build or docker image')
    }
    environment {
        BUILD_ID="dontKillMe"
        JENKINS_NODE_COOKIE="dontKillMe"
    }

    stages {
        stage('Setup') {
            agent {
                label "master"
            }
            steps {
                sh '''
                echo "Setup"
                '''

                script {
                    def file = readFile('.go.env')
                    file.split('\n').each { envLine ->
                        def (key, value) = envLine.tokenize('=')
                        env."${key}" = "${value}"
                    }
                }
            }
        }
        stage('Run Tests') {
            parallel {
                stage('DOCKER') {
                    agent {
                        label "docker"
                    }
                    stages('Test on Docker Pkg') {
                        stage('Setup') {
                            steps {
                                printNodeInfo()
                                cleanWs()
                                stopAndRemoveDockers()
                                setupWorkspace()
                            }
                        }
                        stage('Install Docker') {
                            steps {
                                sh '''
                                echo "Installing Docker"
                                curl -O $DOCKER && docker load -i docker_ontap_mcp.tar
                                cp -rf $WORKSPACE/ontap-mcp/integration/test/ontap.yaml .
                                docker run -d \
                                  --name ontap-mcp-server \
                                  -p 8083:8083 \
                                  -v "$(pwd)/ontap.yaml:/opt/mcp/ontap.yaml" \
                                  ghcr.io/netapp/ontap-mcp:latest \
                                  start --port 8083 --host 0.0.0.0

                                # Use an until loop to keep running the command until the condition is met or give up
                                # after 20 attempts
                                max=20
                                url="http://localhost:8083/health"

                                i=1
                                while [ "$i" -le "$max" ]; do
                                  if curl -fsS "$url" >/dev/null 2>&1; then
                                    echo "MCP server Running - Healthy (attempt $i)"
                                    exit 0
                                  fi

                                  echo "Not healthy yet (attempt $i/$max), retrying..."
                                  sleep 1
                                  i=$((i + 1))
                                done

                                echo "Timed out waiting for health after $max attempts"
                                exit 1
                                '''
                            }
                        }
                        stage('Running Test') {
                            steps {
                                sh """
                                export PATH=\$PATH:/usr/local/go/bin
                                export VERSION=$VERSION
                                cd $WORKSPACE/ontap-mcp && just ci
                                """

                            }
                            post {
                                always {
                                    sh """
                                        docker ps -q | xargs docker stop | xargs docker rm --force
                                    """
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

def void stopAndRemoveDockers() {
    sh '''
        for container_id in $(docker ps -a -q);do docker stop $container_id;done
        for container_id in $(docker ps -a -q);do docker rm $container_id;done
        docker system prune --force --volumes
        volumes=$(docker volume ls -qf dangling=true)
        if [ "$volumes" ]; then
            docker volume rm $volumes
        fi
    '''
}

def void setupWorkspace() {
 sh '''
    wget --quiet -O go.tar.gz "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
    rm -rf /usr/local/go && tar -C /usr/local -xzf ./go.tar.gz
    git clone --branch $BRANCH https://$GIT_ONTAP_MCP_TOKEN@github.com/NetApp/ontap-mcp.git
    cp /home/ontapmcpfiles/ontap.yaml $WORKSPACE/ontap-mcp/integration/test/
    cp /home/ontapmcpfiles/.ontap-mcp.env $WORKSPACE/ontap-mcp/integration/test/
    ls -ltra $WORKSPACE/ontap-mcp/integration/test/
'''
}

def void printNodeInfo() {
        def socket = new DatagramSocket()
        socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
        nodeIp = socket.getLocalAddress().getHostAddress();
        println("The Node IP Address is: ${nodeIp}")
}