#!/bin/bash

JENKINS_URL="http://jenkins.fengzhongxing.com/jenkins"
USER="fzxadmin"
PASS="FzxAdmin@2026"
JOB_NAME="Fzx-Deploy"
CONFIG_FILE="fzx-deploy-config.xml"

echo "Getting CSRF crumb..."
CRUMB_RESPONSE=$(curl -s -u "$USER:$PASS" "$JENKINS_URL/crumbIssuer/api/json" -c /tmp/cookie.txt)
CRUMB=$(echo "$CRUMB_RESPONSE" | grep -o '"crumb":"[^"]*"' | cut -d'"' -f4)

if [ -z "$CRUMB" ]; then
    echo "ERROR: Failed to get CSRF crumb"
    exit 1
fi

echo "Updating $JOB_NAME job..."
RESPONSE=$(curl -s -X POST -u "$USER:$PASS" "$JENKINS_URL/job/$JOB_NAME/config.xml" \
  -H "Jenkins-Crumb:$CRUMB" \
  -H "Content-Type: application/xml" \
  -b /tmp/cookie.txt \
  --data-binary @"$CONFIG_FILE" \
  -w "\nHTTP Status: %{http_code}\n")

echo "$RESPONSE"

if echo "$RESPONSE" | grep -q "HTTP Status: 200"; then
    echo "✅ $JOB_NAME job updated successfully!"
else
    echo "❌ Failed to update $JOB_NAME job"
    exit 1
fi
