#!/usr/bin/env python3
import subprocess
import re

# Step 1: Get CSRF token
print("=== Step 1: Getting CSRF token ===")
subprocess.call(["curl", "-s", "-c", "/tmp/jenkins_cookie.txt", "-u", "admin:FzxAdmin@2026", "http://localhost:8080/crumbIssuer/api/xml", "-o", "/dev/null"])

p = subprocess.Popen(
    ["curl", "-s", "-b", "/tmp/jenkins_cookie.txt", "-u", "admin:FzxAdmin@2026", "http://localhost:8080/crumbIssuer/api/xml"],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
xml_content, _ = p.communicate()
xml_content = xml_content.decode('utf-8')

match = re.search(r'<crumb>([^<]+)</crumb>', xml_content)
if match:
    crumb = match.group(1)
    print(f"Got crumb: {crumb[:20]}...")
else:
    print("Failed to get CSRF token")
    exit(1)

# Step 2: Create credential using correct API
print("\n=== Step 2: Creating credential ===")
credential_xml = '''
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
  <scope>GLOBAL</scope>
  <id>registry-cred</id>
  <description>Private registry credentials for image push</description>
  <username>admin</username>
  <password>Registry@Fzx2026</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
'''

p = subprocess.Popen([
    "curl", "-s", "-b", "/tmp/jenkins_cookie.txt", "-u", "admin:FzxAdmin@2026",
    "-H", "Jenkins-Crumb:" + crumb,
    "-H", "Content-Type: application/xml",
    "-X", "POST",
    "http://localhost:8080/credentials/store/system/domain/_/createCredentials",
    "-d", credential_xml
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print(f"Create status: {p.returncode}")
if stderr:
    print(f"stderr: {stderr[:500]}")

# Verify creation
print("\n=== Step 3: Verifying credential ===")
p = subprocess.Popen([
    "curl", "-s", "-b", "/tmp/jenkins_cookie.txt", "-u", "admin:FzxAdmin@2026",
    "http://localhost:8080/credentials/store/system/domain/_/credential/registry-cred/api/json"
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, _ = p.communicate()
if b'"id":"registry-cred"' in stdout:
    print("✅ Credential created successfully!")
else:
    print("❌ Credential creation failed")
    print(f"Response: {stdout[:500]}")
