#!/usr/bin/env bash
set -euo pipefail

IP="${1:-}"
DAYS="${2:-365}"

if [[ -z "${IP}" ]]; then
  echo "Usage: $0 <IP> [days=365]" >&2
  exit 1
fi

# Detect base64 no-wrap flag (Linux vs macOS)
b64_nowrap() {
  if base64 --help 2>&1 | grep -q -- '--wrap'; then
    base64 --wrap=0
  elif base64 --help 2>&1 | grep -q -- '-w'; then
    base64 -w0
  else
    # macOS/BSD base64 has no wrap-control: remove newlines
    base64 | tr -d '\n'
  fi
}

mkdir -p out
cd out

echo "[*] Generating CA key/cert..."
openssl genrsa -out ca.key 2048 >/dev/null 2>&1
openssl req -x509 -new -nodes -key ca.key -sha256 -days "${DAYS}" -out ca.crt \
  -subj "/C=US/ST=NA/L=NA/O=CustomOrg/OU=CustomUnit/CN=CustomRootCA" >/dev/null 2>&1

echo "[*] Generating server key/CSR for IP: ${IP} ..."
openssl genrsa -out server.key 2048 >/dev/null 2>&1
openssl req -new -key server.key -out server.csr \
  -subj "/C=US/ST=NA/L=NA/O=CustomOrg/OU=CustomUnit/CN=${IP}" >/dev/null 2>&1

# Create a temporary OpenSSL config for SAN (portable across OpenSSL versions)
cat > san.cnf <<EOF
[ req ]
default_bits       = 2048
distinguished_name = dn
req_extensions     = req_ext
prompt             = no

[ dn ]
C  = US
ST = NA
L  = NA
O  = CustomOrg
OU = CustomUnit
CN = ${IP}

[ req_ext ]
subjectAltName = IP:${IP}

[ v3_ext ]
subjectAltName = IP:${IP}
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
EOF

echo "[*] Signing server cert with CA (incl. IP SAN)..."
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -out server.crt -days "${DAYS}" -sha256 -extfile san.cnf -extensions v3_ext >/dev/null 2>&1

# Base64 (no newlines)
echo "[*] Encoding to base64 for Palette..."
b64_nowrap < server.crt > cert.b64
b64_nowrap < server.key > key.b64
b64_nowrap < ca.crt     > ca.b64

# Create a handy JSON blob you can copy as well
cat > palette.json <<JSON
{
  "systemAddress": "https://${IP}",
  "certificate_b64": "$(cat cert.b64)",
  "key_b64": "$(cat key.b64)",
  "ca_b64": "$(cat ca.b64)"
}
JSON

echo
echo "=== Palette Fields (copy/paste) ==="
echo "System Address: https://${IP}"
echo
echo "Certificate (base64):"
cat cert.b64; echo
echo
echo "Key (base64):"
cat key.b64; echo
echo
echo "CA (base64):"
cat ca.b64; echo
echo
echo "Files written to: $(pwd)"
echo "  - ca.key, ca.crt, ca.srl"
echo "  - server.key, server.csr, server.crt"
echo "  - cert.b64, key.b64, ca.b64"
echo "  - palette.json"
