#!/usr/bin/env bash
# =============================================================================
# btp_key2pse.sh  -  SAP BTP service key (X.509)  ->  SSL client PSE for STRUST
# Version 2.4.0 - Vladimir Savekov, https://www.vs.tsgsap.com
# Provided as is, without warranty. Test it on a non-production system first.
#
# Run on an SAP application server as <sid>adm (needs openssl + sapgenpse).
# Works interactively (asks for everything it is not given) or fully from
# the command line.
#
# Source of the service key - one of:
#   A) BTP CLI (default): logs on, lets you pick subaccount -> instance -> key
#      and downloads the key straight into the shredded temp folder.
#      Keys of Cloud Foundry instances are not visible to the btp CLI - for
#      those the script switches to the cf CLI automatically (org and API
#      endpoint are read from the subaccount, then cf login if needed).
#   B) -k key.json: a key you already downloaded
#
#   ./btp_key2pse.sh [-g ga-subdomain] [-a subaccount] [-i instance] [-b key]
#                    [-n pse-name] [-w tempdir] [-s secudir]
#                    [-t host[:port]] [-P proxy|none] [-B btp-dir] [-C cf-dir]
#                    [-R auto|sm|cf] [-S] [-d]
#   ./btp_key2pse.sh -k key.json -n BTP_CPI [-w ...] [-s ...] [-t ...] [-d]
#
#   BTP CLI options
#   -g  global account subdomain (for btp login, only if not logged on)
#   -a  subaccount - display name, subdomain or GUID
#   -i  service instance name (or ID) that holds the key
#   -b  service key (binding) name (or ID)
#   -S  log on with SSO (btp login --sso manual: prints a URL to open)
#   -B  folder of the btp executable
#       (default: $K2P_BTP_DIR, else btp found in PATH, else asked)
#   -P  proxy host:port, or "none"
#       (default: $K2P_PROXY, else the shell's HTTPS_PROXY, else asked in
#       menu mode, else no proxy)
#   -U  btp CLI server URL               (default: https://cli.btp.cloud.sap)
#   -C  folder of the cf executable
#       (default: $K2P_CF_DIR, else the btp folder if cf is there, else PATH)
#   -R  where to read service keys: auto (default: btp CLI, then Cloud
#       Foundry if the instance has no keys there), sm (btp CLI only),
#       cf (Cloud Foundry only)
#
#   General options
#   -k  service key JSON file instead of the BTP CLI
#   -n  PSE file name without .pse (letters, digits, _ and -); not the
#       STRUST identity - that is chosen at import (Save as SSL client)
#   -w  temp directory for working files (key, p12) - the script makes its
#       own sub-folder in it and shreds only that sub-folder
#   -s  SECUDIR folder: SECUDIR is set to it before sapgenpse runs and the
#       new PSE, CA files and summary are written there
#   -t  target host[:port] - save the CA certificates it presents for STRUST
#       (when the key is picked from the menu, the script offers the host
#       found in the key)
#   -d  with -k: shred the key JSON at the end (contains the private key)
#   -N  no password on the PKCS#12 and no PIN on the PSE (no question asked;
#       press Enter when sapgenpse asks for the password and the PIN)
#   -O  overwrite an existing <name>.pse without asking (otherwise the
#       script asks: overwrite / new name / quit)
#
# At the end the script runs "sapgenpse get_my_name -p <PSE>" and shows it.
#
# Site defaults (optional) - put them in <sid>adm's profile or a wrapper:
#   export K2P_PROXY=proxy.example.com:8080   K2P_BTP_DIR=/path/to/btp-folder
#   export K2P_CF_DIR=/path/to/cf-folder       (only if cf is not next to btp)
#
# Passwords and the PSE PIN are typed in (or left empty) - never passed as
# options.
# The STRUST import itself stays manual (PSE -> Import -> Save as SSL client).
# =============================================================================
set -euo pipefail
umask 077

VERSION="2.4.0"
ORIG_SECUDIR="${SECUDIR:-}"      # SECUDIR of the <sid>adm session = live system PSEs
KEYJSON="" NAME="" TARGET="" PROXY="${K2P_PROXY:-}" DELETE_JSON=0 WORKBASE="" SECU=""
GA="" SUBACC="" INSTANCE="" BINDING="" BTP_DIR="${K2P_BTP_DIR:-}" BTP_URL="${K2P_BTP_URL:-https://cli.btp.cloud.sap}" SSO=0
WARN_DAYS=30
SOURCE_INFO="" BTMP="" WORK=""
CF_DIR="${K2P_CF_DIR:-}" ROUTE="auto" CF="" NOPASS=0 OVERWRITE=0 NEWPSE=""

die()  { echo "ERROR: $*" >&2; exit 1; }
info() { echo ">>> $*"; }
warn() { echo "WARNING: $*" >&2; }
usage(){ sed -n '2,73p' "$0" | sed 's/^# \{0,1\}//'; exit 1; }

while getopts ":k:n:w:s:t:P:x:g:a:i:b:B:U:C:R:SNOdh" opt; do
  case $opt in
    k) KEYJSON=$OPTARG ;;
    n) NAME=$OPTARG ;;
    w) WORKBASE=$OPTARG ;;
    s) SECU=$OPTARG ;;
    t) TARGET=$OPTARG ;;
    P|x) PROXY=$OPTARG ;;
    g) GA=$OPTARG ;;
    a) SUBACC=$OPTARG ;;
    i) INSTANCE=$OPTARG ;;
    b) BINDING=$OPTARG ;;
    B) BTP_DIR=$OPTARG ;;
    U) BTP_URL=$OPTARG ;;
    C) CF_DIR=$OPTARG ;;
    R) ROUTE=$OPTARG ;;
    S) SSO=1 ;;
    d) DELETE_JSON=1 ;;
    N) NOPASS=1 ;;
    O) OVERWRITE=1 ;;
    *) usage ;;
  esac
done
[[ $ROUTE == auto || $ROUTE == sm || $ROUTE == cf ]] || die "-R must be auto, sm or cf"

shred_dir() { [[ -n $1 && -d $1 ]] || return 0; find "$1" -type f -exec shred -u {} \; 2>/dev/null || true; rm -rf "$1"; }
cleanup() { [[ -n $NEWPSE && -e $NEWPSE ]] && shred -u "$NEWPSE" 2>/dev/null; shred_dir "$WORK"; shred_dir "$BTMP"; }
trap cleanup EXIT INT TERM

# ------------------------------------------------ prompts --------------
ask() {   # $1 prompt, $2 default -> answer (~ expanded)
  local a; read -r -p "$1${2:+ [$2]}: " a; a=${a:-$2}; echo "${a/#\~/$HOME}"
}
yes_no() { local a; read -r -p "$1 [y/N]: " a; [[ $a == [yY]* ]]; }

choose() {  # $1 title, $2 TSV file "id<TAB>name<TAB>info", $3 preselect -> prints id
  local title=$1 file=$2 pre=$3 n i id name rest pick
  n=$(grep -c . "$file" || true)
  (( n > 0 )) || die "no $title found"
  if [[ -n $pre ]]; then
    id=$(awk -F'\t' -v p="$pre" '$1==p || $2==p {print $1; exit}' "$file")
    if [[ -z $id ]]; then
      echo "Available ${title}s:" >&2; cut -f2,3 "$file" | sed 's/\t/   /; s/^/   /' >&2
      die "$title '$pre' not found"
    fi
    echo "$id"; return
  fi
  if (( n == 1 )); then
    IFS=$'\t' read -r id name rest _x < "$file"
    echo "    Only one $title: $name  $rest" >&2
    echo "$id"; return
  fi
  echo >&2; echo "Select the $title:" >&2
  i=0
  while IFS=$'\t' read -r id name rest _x; do
    i=$((i+1)); printf '  %3d) %-45s %s\n' "$i" "$name" "$rest" >&2
  done < "$file"
  while :; do
    read -r -p "Number (1-$n): " pick || die "no selection"
    [[ $pick =~ ^[0-9]+$ ]] && (( pick >= 1 && pick <= n )) && break
    echo "    please enter a number between 1 and $n" >&2
  done
  sed -n "${pick}p" "$file" | cut -f1
}
name_of() { awk -F'\t' -v i="$2" '$1==i {print $2; exit}' "$1"; }

# ---------------------------------------------------------------- tools -----
command -v openssl >/dev/null || die "openssl not found"
SAPGENPSE=$(command -v sapgenpse || true)
if [[ -z $SAPGENPSE && -n ${SAPSYSTEMNAME:-} && -x /usr/sap/$SAPSYSTEMNAME/SYS/exe/run/sapgenpse ]]; then
  SAPGENPSE=/usr/sap/$SAPSYSTEMNAME/SYS/exe/run/sapgenpse
fi
[[ -n $SAPGENPSE ]] || die "sapgenpse not found - run as <sid>adm"

PY=""
for p in python3 /usr/libexec/platform-python; do
  if command -v "$p" >/dev/null 2>&1; then PY=$(command -v "$p"); break; fi
done
[[ -n $PY ]] || command -v jq >/dev/null || die "need python3 (or platform-python) or jq to read JSON"

# JSON helper - modes: subaccounts | instances | bindings <inst-id> | credentials <out> | urlhost
pyj() {
  [[ -n $PY ]] || die "python3 / platform-python is needed for the BTP CLI part"
  "$PY" - "$@" <<'PY'
import json, sys
from urllib.parse import urlparse
from urllib.parse import quote
mode, path = sys.argv[1], sys.argv[2]
if mode == 'q':                       # URL-encode a value
    print(quote(path, safe='')); sys.exit(0)
d = json.load(open(path))
if mode.startswith('cf') and isinstance(d, dict) and d.get('errors'):
    e = d['errors'][0]
    sys.stderr.write('Cloud Foundry API: %s %s\n' % (e.get('title', ''), e.get('detail', '')))
    sys.exit(4)
def items(o):
    if isinstance(o, list): return o
    if isinstance(o, dict):
        for k in ('value', 'items', 'resources', 'subaccounts', 'service_instances', 'service_bindings', 'environmentInstances'):
            if isinstance(o.get(k), list): return o[k]
    return []
def row(*f): print('\t'.join('' if x is None else str(x).replace('\t', ' ') for x in f))
def key(s, f): return str(s.get(f) or '').lower()
if mode == 'subaccounts':
    for s in sorted(items(d), key=lambda s: key(s, 'displayName')):
        row(s.get('guid'), s.get('displayName'), '%s  %s' % (s.get('region') or '', s.get('subdomain') or ''))
elif mode == 'instances':
    for s in sorted(items(d), key=lambda s: key(s, 'name')):
        row(s.get('id'), s.get('name'), (s.get('created_at') or '')[:10])
elif mode == 'bindings':
    inst = sys.argv[3]
    for s in sorted(items(d), key=lambda s: key(s, 'name')):
        if s.get('service_instance_id') == inst:
            row(s.get('id'), s.get('name'), (s.get('created_at') or '')[:10])
elif mode == 'cfenv':                 # CF environments of a subaccount: id, org, api, org-id
    for s in items(d):
        if str(s.get('environmentType', '')).lower() != 'cloudfoundry': continue
        lab = s.get('labels') or {}
        if isinstance(lab, str):
            try: lab = json.loads(lab)
            except ValueError: lab = {}
        lab = {str(k).lower().replace(':', '').strip(): v for k, v in lab.items()}
        api = lab.get('api endpoint') or ''
        org = lab.get('org name') or s.get('name') or ''
        if api: row(s.get('id'), org, api, lab.get('org id') or '')
elif mode == 'cfguid':
    r = items(d)
    if r: print(r[0].get('guid', ''))
elif mode == 'cfkeys':
    for s in sorted(items(d), key=lambda s: key(s, 'name')):
        row(s.get('guid'), s.get('name'), (s.get('created_at') or '')[:10])
elif mode == 'credentials':
    c = d.get('credentials') if isinstance(d, dict) else None
    if not c: sys.exit(3)
    json.dump(c, open(sys.argv[3], 'w'))
elif mode == 'urlhost':
    c = d.get('credentials', d) if isinstance(d, dict) else {}
    for o in (c.get('oauth'), c):
        u = o.get('url') if isinstance(o, dict) else None
        if isinstance(u, str) and u.startswith('https://'):
            print(urlparse(u).hostname); break
PY
}

# ------------------------------------------------ 1. proxy --------------
if [[ -z $PROXY ]]; then
  SHELL_PROXY=${HTTPS_PROXY:-${https_proxy:-}}
  if [[ -n $SHELL_PROXY ]]; then
    PROXY=${SHELL_PROXY#*://}; PROXY=${PROXY%/}
    echo "    proxy taken from the shell's HTTPS_PROXY" >&2
  elif [[ -z $BINDING && ( -z $KEYJSON || -n $TARGET ) ]]; then   # menu mode: ask
    PROXY=$(ask "Proxy host:port (Enter = no proxy)" "")
  fi
fi
if [[ -n $PROXY && $PROXY != none ]]; then
  export HTTPS_PROXY="http://$PROXY" HTTP_PROXY="http://$PROXY" https_proxy="http://$PROXY" http_proxy="http://$PROXY"
  export NO_PROXY="localhost,127.0.0.1" no_proxy="localhost,127.0.0.1"
  info "Proxy: $PROXY"
else
  PROXY=""
  unset HTTPS_PROXY HTTP_PROXY https_proxy http_proxy ALL_PROXY all_proxy
  info "Proxy: none (proxy variables cleared)"
fi

# ------------------------------------------------ 2-6. key from BTP ------
if [[ -z $KEYJSON ]]; then
  # 2. BTP CLI environment
  if [[ -z $BTP_DIR ]]; then
    if command -v btp >/dev/null; then BTP_DIR=$(dirname "$(command -v btp)")
    else BTP_DIR=$(ask "Folder of the btp executable" ""); fi
  fi
  [[ -n $BTP_DIR && -x $BTP_DIR/btp ]] || die "btp executable not found in '${BTP_DIR}' (use -B <folder> or K2P_BTP_DIR)"
  export PATH="$BTP_DIR:$PATH"
  info "BTP CLI: $(command -v btp)  ($(btp --version 2>/dev/null | grep -m1 -i -E 'v[0-9]|version' || echo 'version unknown'))"
  BTMP=$(mktemp -d "${TMPDIR:-/tmp}/btp_cli.XXXXXX")       # listings + downloaded key, shredded

  # logged on? otherwise btp login
  if ! btp --format json list accounts/subaccount >"$BTMP/sub.json" 2>"$BTMP/err.txt"; then
    info "Not logged on to the BTP CLI - starting btp login"
    [[ -n $GA ]] || GA=$(ask "Global account subdomain (Enter = btp asks)" "")
    LOGIN=(login --url "$BTP_URL")
    [[ -n $GA ]] && LOGIN+=(--subdomain "$GA")
    (( SSO )) && LOGIN+=(--sso manual)
    btp "${LOGIN[@]}" || die "btp login failed"
    btp --format json list accounts/subaccount >"$BTMP/sub.json" 2>"$BTMP/err.txt" \
      || die "cannot list subaccounts: $(head -3 "$BTMP/err.txt")"
  fi

  # 3. subaccount
  pyj subaccounts "$BTMP/sub.json" > "$BTMP/sub.tsv"
  if [[ -n $SUBACC ]]; then          # subdomain is accepted as a selector too
    m=$(awk -F'\t' -v p="$SUBACC" '{split($3,a,"  ")} a[2]==p {print $1; exit}' "$BTMP/sub.tsv")
    [[ -n $m ]] && SUBACC=$m
  fi
  SUB_ID=$(choose "subaccount" "$BTMP/sub.tsv" "$SUBACC")
  SUB_NAME=$(name_of "$BTMP/sub.tsv" "$SUB_ID")
  info "Subaccount: $SUB_NAME ($SUB_ID)"

  # 4. service instance
  btp --format json list services/instance --subaccount "$SUB_ID" >"$BTMP/inst.json" 2>"$BTMP/err.txt" \
    || die "cannot list service instances: $(head -3 "$BTMP/err.txt")"
  pyj instances "$BTMP/inst.json" > "$BTMP/inst.tsv"
  INST_ID=$(choose "service instance" "$BTMP/inst.tsv" "$INSTANCE")
  INST_NAME=$(name_of "$BTMP/inst.tsv" "$INST_ID")
  info "Service instance: $INST_NAME ($INST_ID)"

  # 5. service key - btp CLI (Service Manager) first, Cloud Foundry if the instance's keys live there
  cf_keys() {
    if [[ -z $CF_DIR ]]; then
      if [[ -x $BTP_DIR/cf ]]; then CF_DIR=$BTP_DIR
      elif command -v cf >/dev/null; then CF_DIR=$(dirname "$(command -v cf)")
      else CF_DIR=$(ask "Folder of the cf executable" ""); fi
    fi
    [[ -n $CF_DIR && -x $CF_DIR/cf ]] || die "cf executable not found in '${CF_DIR}' (use -C <folder> or K2P_CF_DIR)"
    CF="$CF_DIR/cf"
    info "CF CLI: $CF  ($("$CF" version 2>/dev/null | head -1 || echo 'version unknown'))"

    btp --format json list accounts/environment-instance --subaccount "$SUB_ID" >"$BTMP/env.json" 2>"$BTMP/err.txt" \
      || die "cannot read the environments of '$SUB_NAME': $(head -3 "$BTMP/err.txt")"
    pyj cfenv "$BTMP/env.json" > "$BTMP/env.tsv"
    grep -q . "$BTMP/env.tsv" || die "subaccount '$SUB_NAME' has no Cloud Foundry environment"
    local env_id
    env_id=$(choose "Cloud Foundry environment" "$BTMP/env.tsv" "")
    IFS=$'\t' read -r _ CF_ORG CF_API CF_ORG_ID < <(awk -F'\t' -v i="$env_id" '$1==i' "$BTMP/env.tsv")
    info "Cloud Foundry: org '$CF_ORG', API $CF_API"

    # logged on to this API? otherwise cf login (cf asks for user/password or SSO passcode, and the space)
    if ! "$CF" api 2>/dev/null | grep -q -F "$CF_API" || ! "$CF" oauth-token >/dev/null 2>&1; then
      info "Not logged on to $CF_API - starting cf login"
      local cfl=(login -a "$CF_API" -o "$CF_ORG")
      (( SSO )) && cfl+=(--sso)
      "$CF" "${cfl[@]}" || die "cf login failed"
    fi

    if [[ -z $CF_ORG_ID ]]; then
      "$CF" curl "/v3/organizations?names=$(pyj q "$CF_ORG")" >"$BTMP/cforg.json" || die "cf curl failed"
      CF_ORG_ID=$(pyj cfguid "$BTMP/cforg.json") || die "cannot read org '$CF_ORG'"
      [[ -n $CF_ORG_ID ]] || die "org '$CF_ORG' not found - does your user have a role in it?"
    fi
    "$CF" curl "/v3/service_instances?names=$(pyj q "$INST_NAME")&organization_guids=$CF_ORG_ID" >"$BTMP/cfinst.json" || die "cf curl failed"
    CF_INST=$(pyj cfguid "$BTMP/cfinst.json") || die "cannot look up instance '$INST_NAME'"
    [[ -n $CF_INST ]] || die "instance '$INST_NAME' not found in org '$CF_ORG' - do you have a role in its space?"
    "$CF" curl "/v3/service_credential_bindings?type=key&service_instance_guids=$CF_INST&per_page=200" >"$BTMP/cfkeys.json" || die "cf curl failed"
    pyj cfkeys "$BTMP/cfkeys.json" > "$BTMP/bind.tsv" || die "cannot list the service keys of '$INST_NAME'"
    grep -q . "$BTMP/bind.tsv" || die "no service keys found for '$INST_NAME' in Cloud Foundry either"
  }

  ROUTE_USED=""
  if [[ $ROUTE != cf ]]; then
    if btp --format json list services/binding --subaccount "$SUB_ID" >"$BTMP/bind.json" 2>"$BTMP/err.txt"; then
      pyj bindings "$BTMP/bind.json" "$INST_ID" > "$BTMP/bind.tsv"
    else
      warn "btp CLI could not list service keys: $(head -1 "$BTMP/err.txt")"; : > "$BTMP/bind.tsv"
    fi
    if grep -q . "$BTMP/bind.tsv"; then ROUTE_USED=sm
    elif [[ $ROUTE == sm ]]; then die "the btp CLI shows no service keys for '$INST_NAME' (Cloud Foundry keys: use -R cf or -R auto)"
    else info "No service keys for '$INST_NAME' via the btp CLI - reading them from Cloud Foundry"; fi
  fi
  if [[ -z $ROUTE_USED ]]; then cf_keys; ROUTE_USED=cf; fi

  BIND_ID=$(choose "service key" "$BTMP/bind.tsv" "$BINDING")
  BIND_NAME=$(name_of "$BTMP/bind.tsv" "$BIND_ID")
  info "Service key: $BIND_NAME ($BIND_ID)"

  # 6. download - stays in the shredded temp folder, never printed
  if [[ $ROUTE_USED == sm ]]; then
    btp --format json get services/binding "$BIND_ID" --subaccount "$SUB_ID" >"$BTMP/binding.json" 2>"$BTMP/err.txt" \
      || die "cannot read the service key: $(head -3 "$BTMP/err.txt")"
    VIA="btp CLI"
  else
    "$CF" curl "/v3/service_credential_bindings/$BIND_ID/details" >"$BTMP/binding.json" 2>"$BTMP/err.txt" \
      || die "cannot read the service key: $(head -3 "$BTMP/err.txt")"
    pyj cfguid "$BTMP/binding.json" >/dev/null || die "Cloud Foundry refused the key details (needs the Space Developer role in the instance's space)"
    VIA="cf CLI, org '$CF_ORG'"
  fi
  pyj credentials "$BTMP/binding.json" "$BTMP/key.json" \
    || die "no credentials returned for '$BIND_NAME' - download it in the cockpit and rerun with -k"
  KEYJSON="$BTMP/key.json"
  info "Service key downloaded via $VIA (temporary, shredded at the end)"
  SOURCE_INFO="BTP subaccount '$SUB_NAME' ($SUB_ID), instance '$INST_NAME', key '$BIND_NAME' (via $VIA)"

  [[ -n $NAME ]] || NAME=$(ask "PSE file name (without .pse)" "$(printf '%s' "$BIND_NAME" | tr -c 'A-Za-z0-9_-' '_' | cut -c1-40)")
  if [[ -z $TARGET && -z $BINDING ]]; then      # only asked when the key was picked from the menu
    H=$(pyj urlhost "$BTMP/binding.json" || true)
    if [[ -n $H ]] && yes_no "Fetch the CA certificates of $H for STRUST?"; then TARGET=$H; fi
  fi
else
  [[ -r $KEYJSON ]] || die "cannot read $KEYJSON"
  SOURCE_INFO="file $KEYJSON"
  [[ -n $NAME ]] || NAME=$(ask "PSE file name (without .pse)" "")
fi

check_name() {
  [[ $1 =~ ^[A-Za-z0-9_-]{1,40}$ ]] || die "name may only contain letters, digits, _ and - (max 40)"
  case "${1^^}" in
    SAPSSLS|SAPSSLC|SAPSSLA|SAPSYS|SAPSRV|SAPSNCS|SAPSSLC_*|SAPSSLS_*|SAPSSLA_*)
      die "'$1' is a reserved system PSE name - choose another name" ;;
  esac
}
check_name "$NAME"

# ------------------------------------------------ folders -------------
is_sap_sec() {   # live SAP sec directory?
  local d=$1
  [[ $d == /usr/sap/*/sec* || $d == /usr/sap/*/*/sec* ]] && return 0
  [[ -n $ORIG_SECUDIR && -d $ORIG_SECUDIR && $d == "$(cd "$ORIG_SECUDIR" && pwd -P)" ]] && return 0
  [[ -e $d/SAPSSLS.pse || -e $d/SAPSYS.pse || -e $d/SAPSSLC.pse ]] && return 0
  return 1
}
prepare_dir() {  # $1 path, $2 label, $3 1=given as option (create without asking)
  local d=$1
  if [[ ! -d $d ]]; then
    if [[ ${3:-0} == 1 ]]; then echo "    creating $2 $d" >&2
    else yes_no "$2 '$d' does not exist - create it?" >&2 || die "$2 not created"; fi
    mkdir -p "$d" || die "cannot create $d"
    chmod 700 "$d"
  fi
  [[ -w $d ]] || die "$2 '$d' is not writable for $(id -un)"
  (cd "$d" && pwd -P)
}

echo
W_OPT=0; [[ -n $WORKBASE ]] && W_OPT=1
[[ -n $WORKBASE ]] || WORKBASE=$(ask "Temp directory for working files (key, p12)" "${TMPDIR:-/tmp}")
WORKBASE=$(prepare_dir "$WORKBASE" "temp directory" $W_OPT)
is_sap_sec "$WORKBASE" && die "temp directory '$WORKBASE' is an SAP sec directory - choose another one"

S_OPT=0; [[ -n $SECU ]] && S_OPT=1
[[ -n $SECU ]] || SECU=$(ask "SECUDIR folder for sapgenpse (new PSE is written here)" "$HOME/btp_pse_${NAME}_$(date +%Y%m%d)")
SECU=$(prepare_dir "$SECU" "SECUDIR folder" $S_OPT)
is_sap_sec "$SECU" && die "SECUDIR '$SECU' is the system's sec directory (or holds SAPSSLS/SAPSYS/SAPSSLC.pse) - choose a separate folder"
[[ -n $ORIG_SECUDIR ]] && echo "    Session SECUDIR (left untouched): $ORIG_SECUDIR"
chmod 700 "$SECU" 2>/dev/null || warn "could not set 700 on $SECU"

while :; do
  PSE="$SECU/$NAME.pse"
  [[ -e $PSE ]] || break
  if (( OVERWRITE )); then warn "$PSE exists - it will be overwritten"; break; fi
  warn "$PSE already exists."
  read -r -p "    [o]verwrite it, enter a [n]ew name, or [q]uit? [o/n/q]: " ans || die "no answer"
  case $ans in
    o|O) OVERWRITE=1; break ;;
    n|N) NAME=$(ask "New PSE file name (without .pse)" ""); check_name "$NAME" ;;
    *)   die "stopped by user - nothing changed" ;;
  esac
done
OTHER_PSE=$(find "$SECU" -maxdepth 1 -name '*.pse' ! -name "$NAME.pse" 2>/dev/null | head -5)
if [[ -n $OTHER_PSE ]]; then
  echo "    Note: other PSE files in this SECUDIR folder (left untouched):" >&2
  echo "$OTHER_PSE" | sed 's/^/      /' >&2
fi

WORK=$(mktemp -d "$WORKBASE/btp_pse.XXXXXX")   # own sub-folder - only this is shredded
echo "    Working files : $WORK (shredded at the end)"
echo "    SECUDIR       : $SECU"
echo "    New PSE       : $PSE"
echo

# --------------------------------------------- 7a. extract cert + key ------
info "Reading the service key"
extract() {   # $1 = field name, finds it at any depth (e.g. under "oauth")
  if [[ -n $PY ]]; then
    "$PY" - "$KEYJSON" "$1" <<'PY'
import json, sys
def find(o, k):
    if isinstance(o, dict):
        if isinstance(o.get(k), str): return o[k]
        o = list(o.values())
    if isinstance(o, list):
        for v in o:
            r = find(v, k)
            if r: return r
r = find(json.load(open(sys.argv[1])), sys.argv[2])
if not r: sys.exit(1)
sys.stdout.write(r)
PY
  else
    jq -er --arg f "$1" '[..|objects|.[$f]? // empty|strings][0]' "$KEYJSON"
  fi
}
extract certificate > "$WORK/cert.pem" || die "no 'certificate' field in the service key - was it created with key type Certificate / X.509?"
extract key         > "$WORK/key.pem"  || die "no 'key' field (private key) in the service key"

# --------------------------------------------- 7b. checks ------------------
NCERT=$(grep -c 'BEGIN CERTIFICATE' "$WORK/cert.pem" || true)
grep -q 'PRIVATE KEY-----' "$WORK/key.pem" || die "the 'key' field is not a PEM private key"
(( NCERT >= 1 )) || die "no PEM certificate found in the 'certificate' field"
(( NCERT >= 2 )) || warn "only $NCERT certificate in the chain - issuer CAs will be missing in STRUST"

openssl x509 -in "$WORK/cert.pem" -noout >/dev/null 2>&1 || die "openssl cannot read the certificate"
openssl pkey -in "$WORK/key.pem"  -noout >/dev/null 2>&1 || die "openssl cannot read the private key"

CERT_PUB=$(openssl x509 -in "$WORK/cert.pem" -noout -pubkey | openssl sha256)
KEY_PUB=$(openssl pkey -in "$WORK/key.pem" -pubout | openssl sha256)
[[ $CERT_PUB == "$KEY_PUB" ]] || die "certificate and private key do not belong together"

SUBJECT=$(openssl x509 -in "$WORK/cert.pem" -noout -subject | sed 's/^subject= *//')
ISSUER=$(openssl x509 -in "$WORK/cert.pem" -noout -issuer  | sed 's/^issuer= *//')
NOTAFTER=$(openssl x509 -in "$WORK/cert.pem" -noout -enddate | cut -d= -f2)
openssl x509 -in "$WORK/cert.pem" -noout -checkend 0 >/dev/null || die "client certificate already expired ($NOTAFTER)"
openssl x509 -in "$WORK/cert.pem" -noout -checkend $((WARN_DAYS*86400)) >/dev/null || \
  warn "client certificate expires within $WARN_DAYS days ($NOTAFTER)"

info "Client certificate OK"
echo "    Subject : $SUBJECT"
echo "    Issuer  : $ISSUER"
echo "    Expires : $NOTAFTER"
echo "    Chain   : $NCERT certificate(s), key matches certificate"

# --------------------------------------------- 7c. PKCS#12 -----------------
OSSL_MAJOR=$(openssl version | awk '{print $2}' | cut -d. -f1)
P12_OPTS=()
if (( OSSL_MAJOR >= 3 )); then
  # OpenSSL 3 defaults (AES-256/PBKDF2) are not readable by older SAP crypto libs
  P12_OPTS=(-certpbe PBE-SHA1-3DES -keypbe PBE-SHA1-3DES -macalg sha1)
fi

echo
if (( NOPASS )); then
  P12PASS=""
  info "No password / no PIN (-N)"
else
  echo "Transport password for the temporary PKCS#12 file - press Enter for none."
  echo "(With none, also press Enter when sapgenpse asks for the password and the PIN.)"
  read -r -s -p "Transport password (Enter = none): " P12PASS; echo
  if [[ -n $P12PASS ]]; then
    read -r -s -p "Repeat                           : " P12PASS2; echo
    [[ $P12PASS == "$P12PASS2" ]] || die "passwords are different"
    unset P12PASS2
  fi
fi
export P12PASS

openssl pkcs12 -export "${P12_OPTS[@]}" \
  -in "$WORK/cert.pem" -inkey "$WORK/key.pem" \
  -name "$NAME" -out "$WORK/$NAME.p12" -passout env:P12PASS \
  || die "openssl pkcs12 -export failed"
[[ -z $P12PASS ]] && NOPASS=1
unset P12PASS
info "PKCS#12 built ($NAME.p12, temporary)"

# --------------------------------------------- 7d. PSE ---------------------
echo
info "sapgenpse import_p12  ->  $PSE"
if (( NOPASS )); then
  echo "    sapgenpse asks for: 1) the PKCS#12 password -> press Enter"
  echo "                        2) a PIN for the PSE (twice) -> press Enter both times = PSE without PIN"
else
  echo "    sapgenpse asks for: 1) the transport password  2) a NEW PIN for the PSE (twice)"
  echo "    Keep the PIN - STRUST asks for it when you import the PSE (Enter = no PIN)."
fi
NEWPSE="$SECU/.$NAME.new.$$.pse"        # built under a temp name, replaces the old file only on success
( export SECUDIR="$SECU"; cd "$SECU"; echo "    SECUDIR=$SECUDIR"
  "$SAPGENPSE" import_p12 -p "$NEWPSE" "$WORK/$NAME.p12" ) \
  || die "sapgenpse import_p12 failed - see the message above$( [[ -e $PSE ]] && echo " (the existing $NAME.pse was not touched)")"
[[ -s $NEWPSE ]] || die "sapgenpse finished but no PSE was created"
chmod 600 "$NEWPSE"
if [[ -e $PSE ]]; then
  mv -f "$NEWPSE" "$PSE"; NEWPSE=""
  info "PSE overwritten: $PSE"
else
  mv "$NEWPSE" "$PSE"; NEWPSE=""
  info "PSE created: $PSE"
fi

# --------------------------------------------- 7d2. show the PSE ----------
echo
info "sapgenpse get_my_name -p $PSE"
MYNAME=""
if (( NOPASS )); then
  MYNAME=$( export SECUDIR="$SECU"; cd "$SECU"; "$SAPGENPSE" get_my_name -p "$PSE" 2>&1 ) \
    || warn "sapgenpse get_my_name returned an error - see below"
  echo "$MYNAME" | sed 's/^/    /'
else
  echo "    (enter the PSE PIN if sapgenpse asks for it)"
  ( export SECUDIR="$SECU"; cd "$SECU"; "$SAPGENPSE" get_my_name -p "$PSE" ) \
    || warn "sapgenpse get_my_name returned an error - see above"
fi

# --------------------------------------------- 7e. target CA certificates --
CA_LIST=""
if [[ -n $TARGET ]]; then
  HOST=${TARGET%%:*}; PORT=${TARGET##*:}; [[ $PORT == "$TARGET" ]] && PORT=443
  info "Fetching the certificate chain of $HOST:$PORT${PROXY:+ via $PROXY}"
  S_OPTS=(-connect "$HOST:$PORT" -servername "$HOST" -showcerts)
  [[ -n $PROXY ]] && S_OPTS+=(-proxy "$PROXY")
  if openssl s_client "${S_OPTS[@]}" </dev/null >"$WORK/chain.txt" 2>/dev/null \
       && grep -q 'BEGIN CERTIFICATE' "$WORK/chain.txt"; then
    awk -v dir="$WORK" '/BEGIN CERTIFICATE/{n++; f=sprintf("%s/srv_%02d.crt",dir,n)}
                        n && f {print > f} /END CERTIFICATE/{close(f); f=""}' "$WORK/chain.txt"
    i=0
    for f in "$WORK"/srv_*.crt; do
      i=$((i+1))
      s=$(openssl x509 -in "$f" -noout -subject | sed 's/^subject= *//')
      e=$(openssl x509 -in "$f" -noout -enddate | cut -d= -f2)
      if (( i == 1 )); then
        echo "    leaf  : $s (expires $e) - do NOT import, it is renewed regularly"
      else
        out="$SECU/${HOST//[^A-Za-z0-9.-]/_}_CA_$((i-1)).crt"
        cp "$f" "$out"; chmod 644 "$out"
        echo "    CA    : $s (expires $e) -> $out"
        CA_LIST+="  - $out  ($s, expires $e)"$'\n'
      fi
    done
    [[ -z $CA_LIST ]] && warn "server sent only its leaf certificate - get the root CA from the CA's website"
    [[ -n $CA_LIST ]] && echo "    Note: if the chain ends in an intermediate, also import its root CA."
    echo "    Check the CA names: if this server reaches the target through a TLS-inspecting"
    echo "    proxy, you see the proxy's CA, not the target's - then get the CA another way."
  else
    warn "could not reach $HOST:$PORT (check the proxy, -P host:port) - skipped"
  fi
fi

# --------------------------------------------- 7f. summary + clean-up ------
SUMMARY="$SECU/$NAME.summary.txt"
cat > "$SUMMARY" <<EOF
BTP service key -> STRUST SSL client PSE   (btp_key2pse.sh $VERSION)
Created   : $(date '+%Y-%m-%d %H:%M') on $(hostname) by $(id -un)
Source    : $SOURCE_INFO
PSE file  : $PSE
SECUDIR   : $SECU
Identity  : $NAME
Subject   : $SUBJECT
Issuer    : $ISSUER
Expires   : $NOTAFTER      <-- put a renewal reminder 30 days before
Chain     : $NCERT certificate(s)
Target CA :
${CA_LIST:-  (not fetched - run with -t <host> or import the CA manually)}
sapgenpse get_my_name -p $PSE :
$( [[ -n $MYNAME ]] && echo "$MYNAME" | sed 's/^/  /' || echo "  (shown on screen - PSE has a PIN)" )
Next steps (manual, SAP GUI):
  1. Copy $NAME.pse to your PC (secure transfer).$( (( OVERWRITE )) && echo "  NOTE: this run overwrote an older $NAME.pse." )
  2. STRUST -> Environment -> SSL Client Identities -> new identity (renewal: export current PSE first).
  3. STRUST change mode -> PSE -> Import -> $NAME.pse -> PIN -> PSE -> Save as -> SSL Client -> identity.
  4. Same node: Import certificate -> target CA file(s) -> Add to Certificate List -> Save.
     All application servers under the node must be green.
  5. SOAMANAGER -> logical port -> Consumer Security -> X.509 SSL Client Certificate -> identity -> Save.
  6. Test: Ping Web Service AND one real call. Then delete $NAME.pse from the PC and remove $SECU on this server.
EOF
chmod 600 "$SUMMARY"

if [[ -z $BTMP ]]; then
  if (( DELETE_JSON )); then
    shred -u "$KEYJSON" && info "Service key JSON shredded"
  else
    warn "$KEYJSON still contains the private key - delete it when done (shred -u), or rerun with -d"
  fi
fi

echo
info "Done. Summary: $SUMMARY"
echo "    Temporary files (service key, private key, p12) are being shredded now."
