#!/usr/bin/env bash
#
# jenkins-setup.sh — wire the LAN Jenkins to deploy this platform automatically.
# Run from the workstation (needs curl + ssh-keygen). Idempotent.
#
#   JENKINS_USER=<login> JENKINS_TOKEN=<api token> ./ci/jenkins-setup.sh
#
# What it does on Jenkins (REST API; needs only the stock Pipeline, Git,
# SSH Credentials and Credentials Binding plugins):
#   1. generates an ed25519 keypair `jenkins-platform` (kept in ~/.ssh/, only
#      the private half goes to Jenkins as credential PAAS_SSH_CRED)
#   2. creates/updates the pipeline job `paas-platform` from
#      ci/jenkins-platform-job.xml (Pipeline script from SCM →
#      ci/Jenkinsfile.platform, polls every 2 min)
# Then it prints the ONE command to run on the paas server to authorize the
# key (infra/setup-ci-deploy.sh) — after that every push to main deploys.
#
# Env / overrides:
#   JENKINS_URL     default http://192.168.12.65:8080
#   REPO_URL        default https://github.com/younex1/deploy-younex-web.git (https, so the
#                   existing GitHub token credential works)
#   GIT_CRED_ID     Jenkins credential that can clone REPO_URL (default: younex1 — the
#                   GitHub token the other jobs on this Jenkins already use)
#   PAAS_SSH_CRED   default paas-platform-deploy (must match ci/Jenkinsfile.platform)
#   JOB_NAME        default paas-platform

set -euo pipefail
: "${JENKINS_USER:?set JENKINS_USER}"; : "${JENKINS_TOKEN:?set JENKINS_TOKEN (Jenkins → user → Security → API token)}"
JENKINS_URL="${JENKINS_URL:-http://192.168.12.65:8080}"
REPO_URL="${REPO_URL:-https://github.com/younex1/deploy-younex-web.git}"
GIT_CRED_ID="${GIT_CRED_ID:-younex1}"
PAAS_SSH_CRED="${PAAS_SSH_CRED:-paas-platform-deploy}"
JOB_NAME="${JOB_NAME:-paas-platform}"
KEY="$HOME/.ssh/jenkins-platform"
XML="$(dirname "$0")/jenkins-platform-job.xml"

api() { curl -sS -f -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
say() { printf '[jenkins-setup] %s\n' "$*"; }

say "Jenkins $(api "$JENKINS_URL/api/json?tree=mode" -o /dev/null -w '%{http_code}' ) at $JENKINS_URL — auth ok"

# ---- 1. keypair + SSH credential ----------------------------------------
if [[ ! -f "$KEY" ]]; then
    ssh-keygen -q -t ed25519 -N '' -C jenkins-platform -f "$KEY"
    say "generated $KEY"
fi
PUB="$(cat "$KEY.pub")"
if api "$JENKINS_URL/credentials/store/system/domain/_/credential/$PAAS_SSH_CRED/api/json" -o /dev/null 2>/dev/null; then
    say "credential $PAAS_SSH_CRED already exists — left as is (delete it in Jenkins to re-create from $KEY)"
else
    json=$(python3 - "$PAAS_SSH_CRED" "$KEY" <<'EOF'
import json, sys
cid, key = sys.argv[1], open(sys.argv[2]).read()
print(json.dumps({"": "0", "credentials": {
  "scope": "GLOBAL", "id": cid, "username": "deploy",
  "description": "paas platform self-deploy key (forced command paas-ci-ssh on the server)",
  "privateKeySource": {"stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource", "privateKey": key},
  "stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"}}))
EOF
)
    api -X POST "$JENKINS_URL/credentials/store/system/domain/_/createCredentials" --data-urlencode "json=$json" -o /dev/null
    say "credential $PAAS_SSH_CRED created (username deploy, key $KEY)"
fi

# ---- 2. job -------------------------------------------------------------
cfg="$(sed -e "s|@@REPO_URL@@|$REPO_URL|" -e "s|@@GIT_CRED_ID@@|$GIT_CRED_ID|" "$XML")"
if api "$JENKINS_URL/job/$JOB_NAME/api/json?tree=name" -o /dev/null 2>/dev/null; then
    api -X POST "$JENKINS_URL/job/$JOB_NAME/config.xml" -H 'Content-Type: application/xml' --data-binary "$cfg" -o /dev/null
    say "job $JOB_NAME updated"
else
    api -X POST "$JENKINS_URL/createItem?name=$JOB_NAME" -H 'Content-Type: application/xml' --data-binary "$cfg" -o /dev/null
    say "job $JOB_NAME created"
fi
say "job: $JENKINS_URL/job/$JOB_NAME/  (repo $REPO_URL via credential '$GIT_CRED_ID')"

cat <<EOF

[jenkins-setup] Last step — authorize the key on the paas server (once per server):

  ssh younes@192.168.13.10 'cd dotnews-paas && sudo ./infra/setup-ci-deploy.sh "$PUB"'

Then push to main (or "Build Now" in Jenkins). Rollback if ever needed:
  ssh younes@192.168.13.10 'sudo paas-self-deploy rollback'
EOF
