#!/usr/bin/env python3
"""
Jenkins配置脚本 - 配置凭证和创建流水线任务
"""

import requests
import json
import base64
import sys
from urllib.parse import quote

# Jenkins配置
JENKINS_URL = "http://localhost:8099"
JENKINS_USER = "fzxadmin"
JENKINS_PASSWORD = "FzxAdmin@2026"

# Git配置
GIT_URL = "https://codeup.aliyun.com/69c68bacfa2a62bc85952a67/FzxBdsh.git"

# 镜像仓库配置
REGISTRY_HOST = "8.140.221.49:5000"

def get_crumb():
    """获取CSRF crumb"""
    try:
        response = requests.get(f"{JENKINS_URL}/crumbIssuer/api/json", auth=(JENKINS_USER, JENKINS_PASSWORD))
        if response.status_code == 200:
            return response.json()
    except Exception as e:
        print(f"⚠️  获取crumb失败: {e}")
    return None

def create_job(job_name, config_xml):
    """创建或更新Jenkins任务"""
    encoded_job_name = quote(job_name, safe='')
    
    crumb = get_crumb()
    headers = {"Content-Type": "application/xml; charset=utf-8"}
    if crumb:
        headers["Jenkins-Crumb"] = crumb["crumbRequestField"]
    
    # 检查任务是否存在
    response = requests.get(
        f"{JENKINS_URL}/job/{encoded_job_name}/config.xml",
        auth=(JENKINS_USER, JENKINS_PASSWORD)
    )
    
    if response.status_code == 200:
        print(f"📝 任务 {job_name} 已存在，正在更新...")
        url = f"{JENKINS_URL}/job/{encoded_job_name}/config.xml"
    else:
        print(f"🆕 创建任务 {job_name}...")
        url = f"{JENKINS_URL}/createItem?name={quote(job_name, safe='')}"
    
    response = requests.post(
        url,
        data=config_xml.encode('utf-8'),
        auth=(JENKINS_USER, JENKINS_PASSWORD),
        headers=headers
    )
    
    if response.status_code in [200, 201, 302]:
        print(f"✅ 任务 {job_name} {'更新' if response.status_code == 200 else '创建'}成功")
        return True
    else:
        print(f"❌ 任务 {job_name} {'更新' if response.status_code == 200 else '创建'}失败: {response.status_code}")
        print(f"   响应: {response.text[:200]}")
        return False

def create_pipeline_job():
    """创建主流水线任务"""
    
    config = '''<?xml version='1.1' encoding='UTF-8'?>
<flow-definition plugin="workflow-job">
  <description>Fzx Platform CI/CD Pipeline</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <jenkins.model.BuildDiscarderProperty>
      <daysToKeep>7</daysToKeep>
      <numToKeep>5</numToKeep>
      <artifactDaysToKeep>7</artifactDaysToKeep>
      <artifactNumToKeep>3</artifactNumToKeep>
    </jenkins.model.BuildDiscarderProperty>
  </properties>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition" plugin="workflow-cps">
    <scm class="hudson.plugins.git.GitSCM" plugin="git">
      <configVersion>2</configVersion>
      <userRemoteConfigs>
        <hudson.plugins.git.UserRemoteConfig>
          <url>{git_url}</url>
          <credentialsId>aliyun-codeup-https</credentialsId>
        </hudson.plugins.git.UserRemoteConfig>
      </userRemoteConfigs>
      <branches>
        <hudson.plugins.git.BranchSpec>
          <name>*/develop</name>
        </hudson.plugins.git.BranchSpec>
      </branches>
    </scm>
    <scriptPath>Jenkinsfile</scriptPath>
    <lightweight>true</lightweight>
  </definition>
  <triggers/>
  <disabled>false</disabled>
</flow-definition>'''.format(git_url=GIT_URL)
    
    return create_job("Fzx-Platform-Pipeline", config)

def create_build_job():
    """创建构建任务"""
    
    # Shell脚本内容
    shell_command = '''#!/bin/bash
set -e

echo "========================================"
echo "Starting Fzx Platform Build"
echo "========================================"

cd /var/jenkins/workspace/Fzx-Build

# Set Maven version
export VERSION="v1.0.0-build-$(date +%Y%m%d%H%M%S)"
echo "Build version: $VERSION"

# Build common-service first
echo "Building common-service..."
cd services/common-service
mvn clean install -DskipTests
cd ../..

# Build other services in parallel
echo "Building microservices..."
for service in api-gateway auth-service user-service map-service order-service merchant-service platform-service product-service rider-service upload-service marketing-service; do
    echo "Building $service..."
    cd services/$service
    mvn clean package -DskipTests
    cd ../..
done

echo "========================================"
echo "Build completed!"
echo "========================================"
'''
    
    config = '''<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description>Fzx Platform Build Job</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <jenkins.model.BuildDiscarderProperty>
      <daysToKeep>7</daysToKeep>
      <numToKeep>5</numToKeep>
      <artifactDaysToKeep>7</artifactDaysToKeep>
      <artifactNumToKeep>3</artifactNumToKeep>
    </jenkins.model.BuildDiscarderProperty>
  </properties>
  <scm class="hudson.plugins.git.GitSCM">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <url>{git_url}</url>
        <credentialsId>aliyun-codeup-https</credentialsId>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>*/develop</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>{shell_command}</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>'''.format(git_url=GIT_URL, shell_command=shell_command)
    
    return create_job("Fzx-Build", config)

def create_deploy_job():
    """创建部署任务"""
    
    shell_command = '''#!/bin/bash
set -e

echo "========================================"
echo "Starting Deploy to Aliyun Dev Environment"
echo "========================================"

DEPLOY_HOST="8.140.221.49"
DEPLOY_USER="root"
SSH_KEY="/var/lib/jenkins/.ssh/id_rsa"

# Deploy backend services
echo "Deploying backend microservices..."
for service in api-gateway auth-service user-service map-service order-service merchant-service platform-service product-service rider-service upload-service marketing-service; do
    echo "Deploying $service..."
    ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$DEPLOY_USER@$DEPLOY_HOST" \\
        "cd /opt/Fzxpodman/infrastructure/compose && podman-compose -f podman-compose.aliyun-dev.yml up -d --build $service" || \\
        echo "$service deployment failed"
done

# Restart infrastructure services
echo "Restarting infrastructure services..."
ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$DEPLOY_USER@$DEPLOY_HOST" \\
    "cd /opt/Fzxpodman/infrastructure/compose && podman-compose -f podman-compose.aliyun-dev.yml restart nginx nacos"

echo "========================================"
echo "Deployment completed!"
echo "========================================"
'''
    
    config = '''<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description>Fzx Platform Deploy Job</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <jenkins.model.BuildDiscarderProperty>
      <daysToKeep>7</daysToKeep>
      <numToKeep>5</numToKeep>
      <artifactDaysToKeep>7</artifactDaysToKeep>
      <artifactNumToKeep>3</artifactNumToKeep>
    </jenkins.model.BuildDiscarderProperty>
  </properties>
  <scm class="hudson.plugins.git.GitSCM">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <url>{git_url}</url>
        <credentialsId>aliyun-codeup-https</credentialsId>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>*/develop</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>{shell_command}</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>'''.format(git_url=GIT_URL, shell_command=shell_command)
    
    return create_job("Fzx-Deploy", config)

def create_simple_build_job():
    """创建简化构建任务（手动触发）"""
    
    config = '''<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description>Fzx Platform Simple Build - Manual Trigger</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <jenkins.model.BuildDiscarderProperty>
      <daysToKeep>7</daysToKeep>
      <numToKeep>5</numToKeep>
    </jenkins.model.BuildDiscarderProperty>
  </properties>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>#!/bin/bash
echo "========================================"
echo "Manual Build Job"
echo "========================================"
echo "This is a placeholder job."
echo "Configure Git credentials first, then trigger build."
</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>'''
    
    return create_job("Fzx-Simple-Build", config)

def main():
    print("="*50)
    print("Jenkins Configuration Script")
    print("="*50)
    
    # 1. Create jobs
    print("\n" + "="*50)
    print("Creating Jenkins Jobs")
    print("="*50)
    
    create_pipeline_job()
    create_simple_build_job()
    create_build_job()
    create_deploy_job()
    
    print("\n" + "="*50)
    print("Jenkins Configuration Completed")
    print("="*50)
    print("\nNext steps:")
    print("1. Configure Git credentials:")
    print("   - Go to: http://jenkins.fengzhongxing.com/manage/credentials/")
    print("   - Add Username/Password credential")
    print("   - ID: aliyun-codeup-https")
    print("   - Username: your Aliyun Codeup username")
    print("   - Password: your Aliyun Codeup password or access token")
    print("\n2. View jobs at: http://jenkins.fengzhongxing.com/")
    print("\n3. Configure SSH credentials for deployment:")
    print("   - Go to: http://jenkins.fengzhongxing.com/manage/credentials/")
    print("   - Add SSH Username with private key credential")
    print("   - ID: aliyun-ssh")
    print("   - Username: root")
    print("   - Private Key: paste your private key content")

if __name__ == "__main__":
    main()
