pipeline {
    agent {
        label 'testframework-2g-2c'
    }

    parameters {
        string(
            name: 'BRANCH',
            defaultValue: 'master',
            description: 'The branch of the SDK repository to build from.'
        )
        string(
            name: 'PYPI_VERSION',
            defaultValue: '',
            description: 'A version identifier used for publishing to PyPI. Example: 5.2.0b1'
        )
        choice(
            name: 'PYPI_INSTANCE',
            choices: ['test', 'production'],
            description: '''Which PyPI instance to publish to.
            <p><b>WARNING: Publishing permanently uses that version number. Be very careful when publishing to production.</b></p>'''
        )
        string(
            name: 'BRANCH_TAG',
            defaultValue: '',
            description: '''<p>This is a postfix to the git tag.</p>
            <p>Default is: "v$PYPI_VERSION", i.e. "v5.2.0b1"</p>
            <p>When BRANCH_TAG is given: PyPI release "v$PYPI_VERSION+$BRANCH_TAG"</p>'''
        )
    }

    environment {
        SDK_VERSION_FILE='python/streamsets/sdk/__version__.py'
        VENV_DIR = "${env.WORKSPACE}/venv"
    }

    stages {
        stage('Build & Publish in Container') {
            agent {
                docker {
                    image 'python:3.10'
                    reuseNode true
                    args '--userns=keep-id --privileged --env CONTAINER_HOST=unix:///run/podman/podman.sock --volume $XDG_RUNTIME_DIR/podman/podman.sock:/run/podman/podman.sock'
                }
            }
            stages {

                stage('Check Parameters') {
                    steps {
                        script {
                            if (!env.PYPI_VERSION?.trim()) {
                                error "No version provided via the PYPI_VERSION environment variable."
                            }

                            withCredentials([
                                string(credentialsId: 'pypi-test-token', variable: 'PYPI_TOKEN_TEST'),
                                string(credentialsId: 'pypi-prod-token', variable: 'PYPI_TOKEN_PROD')
                            ]) {
                                if (env.PYPI_INSTANCE == 'production') {
                                    env.TWINE_USERNAME = '__token__'
                                    env.TWINE_PASSWORD = PYPI_TOKEN_PROD  // pragma: allowlist secret
                                } else if (env.PYPI_INSTANCE == 'test') {
                                    env.TWINE_REPOSITORY_URL = 'https://test.pypi.org/legacy/'
                                    env.TWINE_USERNAME = '__token__'
                                    env.TWINE_PASSWORD = PYPI_TOKEN_TEST  // pragma: allowlist secret
                                } else {
                                    error "Invalid or empty value for PYPI_INSTANCE. Valid options are: {production, test}."
                                }
                            }
                        }
                    }
                }

                stage('Checkout SDK from GitHub') {
                    steps {
                        dir('sdk') {
                            git(
                                url: 'https://github.ibm.com/ibmstreamsets/sdk.git',
                                credentialsId: 'github-streamsetsci',
                                branch: "${params.BRANCH}"
                            )
                        }
                    }
                }

                stage('Ensure git doesnt scream') {
                    steps {
                        sh 'git config --global --add safe.directory ${WORKSPACE}'
                    }
                }

                stage('Install Requirements') {
                    steps {
                        sh '''
                            python3 -m venv "$VENV_DIR"
                            . "$VENV_DIR/bin/activate"
                            export PATH="$HOME/.local/bin:$PATH"
                            pip install --upgrade pip wheel twine pre-commit

                            cd python
                            git config --unset-all core.hooksPath || true
                            make setup
                            cd ../
                        '''
                    }
                }

                stage('Update Version') {
                    steps {
                        sh '''
                            . "$VENV_DIR/bin/activate"
                            echo "Updating version number to: ${PYPI_VERSION}"
                            sed -i.old "s/\\".*\\"/\\"${PYPI_VERSION}\\"/" ${SDK_VERSION_FILE}
                            rm ${SDK_VERSION_FILE}.old
                        '''
                    }
                }

                stage('Build') {
                    steps {
                        sh '''
                            . "$VENV_DIR/bin/activate"
                            cd python
                            echo 'Building'
                            make build
                        '''
                    }
                }

                stage('Upload') {
                    steps {
                        sh '''
                            echo ""
                            echo "Releasing version ${PYPI_VERSION} to the ${PYPI_INSTANCE} PyPI."
                            echo ""
                            . "$VENV_DIR/bin/activate"
                            cd python
                            set +e
                            twine upload --non-interactive dist/*
                            RESULT=$?
                            set -e
                            if [ $RESULT -ne 0 ]; then
                                echo "Twine failed to execute. Cleaning up and bailing." >&2
                                rm -rf dist/ build/ streamsets_testframework.egg-info/
                                exit 1
                            fi
                        '''
                    }
                }

                stage('Cleanup') {
                    steps {
                        sh '''
                            rm -rf dist/ build/ streamsets_testframework.egg-info/ "$VENV_DIR"
                        '''
                    }
                }
            }
        }
    }
}