def commitId = ""
def shortCommitId = ""

def buildBranch = { String b ->
    return (b ?: "").trim()
}

pipeline {
    parameters {
        string(name: 'REMOTE_URL', defaultValue: 'ssh://git@bitbucket.global.renesas.com:7999/conntools/powerprofiler.git', description: 'Default remote url')
        string(name: 'BB_CREDENTIALS_ID', defaultValue: 'ssh_key_connectivity_tools', description: 'Default bitbucket credentials id')
        string(name: 'ARTIFACTORY_SERVER_ID', defaultValue: 'AF_SERVER', description: 'Default artifactory server id')
        string(name: 'ARTIFACTORY_REPOSITORY', defaultValue: 'proj-ConnectivityTools-local', description: 'Default artifactory repository')
        string(name: 'PULL_REQUEST_ID', defaultValue: 'develop', description: 'Pull Request ID')
        string(name: 'PULL_REQUEST_TITLE', defaultValue: 'develop', description: 'Pull Request Title')
        string(name: 'PULL_REQUEST_AUTHOR', defaultValue: 'develop', description: 'Pull Request Author')
        string(name: 'PULL_REQUEST_AUTHOR_EMAIL', defaultValue: 'develop', description: 'Pull Request Author Email')
        string(name: 'TARGET_BRANCH', defaultValue: 'develop', description: 'Target Branch')
        string(name: 'JOB_ID', defaultValue: 'develop', description: 'Job ID')
        string(name: 'BUILD_VERSION', defaultValue: 'x.x.x', description: 'The version noted on the filename')
    }

    agent {
        kubernetes {
            defaultContainer 'node-22-15-0-bullseye'
            yaml '''
apiVersion: v1
kind: Pod
metadata:
  annotations:
    com.cloudbees.sidecar-injector/inject: yes
spec:
  containers:
  - name: "node-22-15-0-bullseye"
    securityContext:
      runAsUser: 0
      runAsGroup: 0
      allowPrivilegeEscalation: false
    image: node:22.15.0-bullseye
    command:
    - sleep
    args:
    - infinity
    resources:
      requests:
        cpu: 2000m
        memory: 2Gi
      limits:
        cpu: 4000m
        memory: 4Gi
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: name
            operator: In
            values:
            - agent-pool
            - PROD-Agent-pool
  tolerations:
  - key: "type"
    operator: "Equal"
    value: "agent-pool"
    effect: "NoSchedule"
'''
        }
    }

    options {
        timestamps()
        skipDefaultCheckout(true)
        disableRestartFromStage()
        preserveStashes(buildCount: 2)
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }

    stages {
        stage('Checkout') {
            steps {
                script {
                    println "Build info: ${JOB_ID}"
                    println "Commit info:"
                    println "PULL_REQUEST_ID: ${PULL_REQUEST_ID}"
                    println "PULL_REQUEST_TITLE: ${PULL_REQUEST_TITLE}"
                    println "PULL_REQUEST_AUTHOR: ${PULL_REQUEST_AUTHOR}"
                    println "PULL_REQUEST_AUTHOR_EMAIL: ${PULL_REQUEST_AUTHOR_EMAIL}"
                    println "TARGET_BRANCH: ${TARGET_BRANCH}"

                    checkout scmGit(
                        branches: [[name: "${buildBranch(TARGET_BRANCH)}"]],
                        submoduleCfg: [],
                        userRemoteConfigs: [[
                            credentialsId: "${BB_CREDENTIALS_ID}",
                            url: "${REMOTE_URL}"
                        ]]
                    )

                    sh 'git config --global --add safe.directory "$PWD"'
                    commitId = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
                    echo "Commit ID from git CLI: ${commitId}"
                }
            }
        }

        stage('Install & Build') {
            steps {
                echo "Build started"
                sh '''#!/usr/bin/env bash
set -euo pipefail

rm -f ./*.vsix
npm run install-all
npm run build-ui
npm run compile
npx @vscode/vsce package --pre-release
'''
                echo "Build finished"
            }
        }

        stage('Deploy Artifacts') {
            steps {
                script {
                    def date = new Date().format('yyyy-MM-dd')
                    def uploadPath = "${ARTIFACTORY_REPOSITORY}/powerprofiler_vsix/Builds/${TARGET_BRANCH}/${date}/"
                    shortCommitId = commitId.take(10)

                    def vsixFile = sh(script: 'ls -1 renesaspowerprofiler-*.vsix | head -n 1', returnStdout: true).trim()
                    if (!vsixFile) {
                        error('No VSIX file found to upload')
                    }

                    rtUpload(
                        serverId: "${ARTIFACTORY_SERVER_ID}",
                        spec: """
                        {
                            "files": [
                                {
                                    "pattern": "${vsixFile}",
                                    "target": "${uploadPath}/RenesasPowerProfiler-${BUILD_VERSION}-build${shortCommitId}.vsix",
                                    "flat": "true"
                                }
                            ]
                        }"""
                    )

                    withCredentials([sshUserPrivateKey(credentialsId: "${BB_CREDENTIALS_ID}", keyFileVariable: 'SSH_KEY')]) {
                        sh """
                        export GIT_SSH_COMMAND="ssh -i \${SSH_KEY} -o StrictHostKeyChecking=no"
                        git config --global --add safe.directory "\${PWD}"
                        git config user.name "${PULL_REQUEST_AUTHOR}"
                        git config user.email "${PULL_REQUEST_AUTHOR_EMAIL}"
                        git tag -a build-${BUILD_NUMBER}-${TARGET_BRANCH} \\
                          -m "Build: ${BUILD_NUMBER}\\nPull Request: ${PULL_REQUEST_ID}\\nCommit: ${commitId}\\nDate: ${date}\\nTitle: ${PULL_REQUEST_TITLE}\\nAuthor: ${PULL_REQUEST_AUTHOR}\\nAuthor Email: ${PULL_REQUEST_AUTHOR_EMAIL}"
                        git push origin --tags
                        """
                    }
                }
            }
        }
    }

    post {
        success {
            script {
                notifyBitbucket(buildStatus: 'SUCCESSFUL', commitSha1: "${commitId}")
            }
        }
        failure {
            script {
                notifyBitbucket(buildStatus: 'FAILED', commitSha1: "${commitId}")
            }
        }
    }
}
