# =============================================================================
# GUARDiA ITSM — Jenkins Configuration as Code (JCasC)
# 적용: sudo cp jenkins.yaml /var/lib/jenkins/casc_configs/ && systemctl restart jenkins
# 필요 플러그인: configuration-as-code, role-strategy, git, pipeline 등
# =============================================================================

jenkins:
  systemMessage: "GUARDiA ITSM CI/CD 서버 — 무단 접근 금지"

  # ── 보안 설정 ────────────────────────────────────────────────────────────
  securityRealm:
    local:
      allowsSignup: false
      users:
        - id: "admin"
          password: "${JENKINS_ADMIN_PASSWORD}"
          properties:
            - mailer:
                emailAddress: "admin@agency.go.kr"
        - id: "itsm-bot"
          password: "${JENKINS_ITSM_BOT_PASSWORD}"
          properties:
            - mailer:
                emailAddress: "itsm-bot@agency.go.kr"

  authorizationStrategy:
    roleBased:
      roles:
        global:
          - name: "admin"
            description: "Jenkins 전체 관리자"
            permissions:
              - "Overall/Administer"
            assignments:
              - "admin"
          - name: "pm"
            description: "PM — 빌드 트리거 및 조회"
            permissions:
              - "Overall/Read"
              - "Job/Build"
              - "Job/Cancel"
              - "Job/Read"
              - "View/Read"
            assignments: []
          - name: "developer"
            description: "개발자 — dev/stg 빌드 트리거"
            permissions:
              - "Overall/Read"
              - "Job/Build"
              - "Job/Read"
              - "Job/Cancel"
              - "View/Read"
            assignments:
              - "itsm-bot"
          - name: "viewer"
            description: "감사 — 읽기 전용"
            permissions:
              - "Overall/Read"
              - "Job/Read"
              - "View/Read"
            assignments: []

  # ── CSRF 보호 ────────────────────────────────────────────────────────────
  crumbIssuer:
    standard:
      excludeClientIPFromCrumb: false

  # ── 전역 환경변수 ────────────────────────────────────────────────────────
  globalNodeProperties:
    - envVars:
        env:
          - key: "ITSM_URL"
            value: "${ITSM_URL}"
          - key: "ITSM_CALLBACK_URL"
            value: "${ITSM_URL}/api/vibe/callback"
          - key: "ARTIFACT_REPO"
            value: "/opt/artifacts"
          - key: "DEPLOY_BASE_PATH"
            value: "/opt/apps"
          - key: "SCRIPTS_ROOT"
            value: "/var/lib/jenkins/scripts"
          # Gitea 설정 (온프레미스 형상관리)
          - key: "GITEA_BASE_URL"
            value: "${GITEA_BASE_URL:-http://localhost:3000}"
          - key: "GITEA_ORG"
            value: "${GITEA_ORG:-guardia}"
          - key: "GITEA_REPO"
            value: "${GITEA_REPO:-GUARDiA}"
          - key: "SCM_BRANCH_PROTECT_MAIN"
            value: "true"
          - key: "DEFAULT_BRANCH"
            value: "main"

  # ── 빌드 실행기 설정 ─────────────────────────────────────────────────────
  numExecutors: 4
  mode: NORMAL
  quietPeriod: 5
  scmCheckoutRetryCount: 2

  # ── 에이전트 설정 (마스터 전용 또는 SSH 에이전트) ─────────────────────────
  nodes:
    - permanent:
        name: "master"
        numExecutors: 2
        remoteFS: "/var/lib/jenkins"
        labelString: "master built-in"
        mode: NORMAL
        retentionStrategy: "always"

  # ── Jenkins URL ───────────────────────────────────────────────────────────
  location:
    url: "${JENKINS_URL}"
    adminAddress: "Jenkins Admin <admin@agency.go.kr>"

# ── 도구 설정 ────────────────────────────────────────────────────────────────
tool:
  jdk:
    installations:
      - name: "JDK17"
        home: "/usr/lib/jvm/java-17-openjdk"
      - name: "JDK21"
        home: "/usr/lib/jvm/java-21-openjdk"

  maven:
    installations:
      - name: "maven3"
        properties:
          - installSource:
              installers:
                - maven:
                    id: "3.9.6"

  gradle:
    installations:
      - name: "gradle8"
        properties:
          - installSource:
              installers:
                - gradleInstaller:
                    id: "8.5"

  nodejs:
    installations:
      - name: "nodejs20"
        properties:
          - installSource:
              installers:
                - nodeJSInstaller:
                    id: "20.11.0"
                    npmPackagesRefreshHours: 72

  git:
    installations:
      - name: "Default"
        home: "/usr/bin/git"

# ── 자격증명 ─────────────────────────────────────────────────────────────────
credentials:
  system:
    domainCredentials:
      - credentials:
          # ITSM API 토큰
          - string:
              scope: GLOBAL
              id: "itsm-api-token"
              description: "GUARDiA ITSM API Token"
              secret: "${ITSM_API_TOKEN}"

          # SonarQube 토큰
          - string:
              scope: GLOBAL
              id: "sonar-token"
              description: "SonarQube 분석 토큰"
              secret: "${SONAR_TOKEN}"

          # Gitea 자격증명 (온프레미스 Git 서버)
          - usernamePassword:
              scope: GLOBAL
              id: "gitea-credentials"
              description: "Gitea 저장소 자격증명 (http://localhost:3000)"
              username: "${GITEA_ADMIN:-gitadmin}"
              password: "${GITEA_ADMIN_PW:-Gitea@guardia!}"

          # Gitea API 토큰 (웹훅 등록 + PR 상태 업데이트)
          - string:
              scope: GLOBAL
              id: "gitea-api-token"
              description: "Gitea Personal Access Token"
              secret: "${GITEA_API_TOKEN}"

          # Git 자격증명 (HTTPS - 하위 호환)
          - usernamePassword:
              scope: GLOBAL
              id: "git-credentials"
              description: "Git 저장소 자격증명 (Gitea 사용 권장)"
              username: "${GIT_USERNAME:-gitadmin}"
              password: "${GIT_PASSWORD}"

# ── SonarQube 서버 설정 ───────────────────────────────────────────────────────
unclassified:
  sonarGlobalConfiguration:
    buildWrapperEnabled: true
    installations:
      - name: "sonarqube"
        serverUrl: "${SONAR_HOST_URL}"
        serverAuthenticationToken: "sonar-token"
        mojoVersion: ""
        additionalAnalysisProperties: ""
        triggers:
          envVar: ""
          skipScmCause: false
          skipUpstreamCause: false

  # ── 이메일 설정 ─────────────────────────────────────────────────────────
  mailServer:
    smtpHost: "${SMTP_HOST}"
    smtpPort: "${SMTP_PORT}"
    authentication:
      username: "${SMTP_USER}"
      password: "${SMTP_PASSWORD}"

  extendedEmailPublisher:
    adminRequiredForTemplateTesting: false
    allowUnregisteredEnabled: false
    charset: "UTF-8"
    debugMode: false
    defaultBody: |
      빌드 결과: $PROJECT_NAME - $BUILD_STATUS
      빌드 번호: $BUILD_NUMBER
      빌드 URL: $BUILD_URL
    defaultContentType: "text/plain"
    defaultSubject: "[GUARDiA CI/CD] $PROJECT_NAME - $BUILD_STATUS"
    defaultTriggerIds:
      - "hudson.plugins.emailext.plugins.trigger.FailureTrigger"
      - "hudson.plugins.emailext.plugins.trigger.FixedTrigger"
    mailAccount:
      smtpHost: "${SMTP_HOST}"
      smtpPort: "${SMTP_PORT}"

  # ── Audit Trail ──────────────────────────────────────────────────────────
  auditTrail:
    logBuildCause: true
    loggers:
      - logFile:
          count: 30
          limit: 100
          log: "/var/log/jenkins/audit.log"
          output: "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %3$s%n"

  # ── Timestamper ──────────────────────────────────────────────────────────
  timestamper:
    allPipelines: true
    elapsedTimeFormat: "'<b>'HH:mm:ss.S'</b> '"
    systemTimeFormat: "'<b>'HH:mm:ss'</b> '"

  # ── 빌드 보관 기본 설정 ─────────────────────────────────────────────────
  defaultFolderConfiguration:
    healthMetrics: []

# ── 파이프라인 Job 자동 생성 (JCasC + Job DSL) ───────────────────────────────
jobs:
  - script: |
      // 파이프라인 폴더 생성
      folder('GUARDiA') {
          description('GUARDiA ITSM CI/CD 파이프라인')
          displayName('GUARDiA ITSM')
      }

      // 기본 배포 파이프라인 (프로젝트별 복사 후 사용)
      pipelineJob('GUARDiA/template-java-maven') {
          description('Java Maven 프로젝트 표준 파이프라인 템플릿')
          definition {
              cpsScm {
                  scm {
                      git {
                          remote {
                              url(System.getenv('GIT_REPO_URL') ?: 'http://git.agency.go.kr/guardia/itsm.git')
                              credentials('git-credentials')
                          }
                          branch('*/main')
                      }
                  }
                  scriptPath('cicd/jenkins/Jenkinsfile.java-maven')
              }
          }
          parameters {
              stringParam('ITSM_SESSION_ID', '', 'GUARDiA 바이브 세션 ID')
              stringParam('ITSM_SR_ID', '', '연결된 SR ID')
              choiceParam('DEPLOY_ENV', ['dev', 'stg', 'prd'], '배포 환경')
              stringParam('TARGET_SERVER', '', '배포 대상 서버명')
              booleanParam('SKIP_TEST', false, '테스트 건너뜀')
          }
      }
