#!/usr/bin/env bash set -Eeuo pipefail # Save Credentials Script # Extracts and saves credentials from installation JSON to a file SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" usage() { cat >&2 <<'EOF' Usage: bash save_credentials.sh --json [options] bash save_credentials.sh --json-file [options] Required (one of): --json JSON string from installation output --json-file Path to file containing JSON Options: --output Output file path (default: credentials/.json) --format Pretty-print JSON output Examples: # Save from JSON string bash save_credentials.sh --json '{"ctid":123,...}' # Save from file bash save_credentials.sh --json-file /tmp/install_output.json # Custom output location bash save_credentials.sh --json-file output.json --output my-credentials.json EOF } # Parse arguments JSON_STRING="" JSON_FILE="" OUTPUT_FILE="" FORMAT=0 while [[ $# -gt 0 ]]; do case "$1" in --json) JSON_STRING="${2:-}"; shift 2 ;; --json-file) JSON_FILE="${2:-}"; shift 2 ;; --output) OUTPUT_FILE="${2:-}"; shift 2 ;; --format) FORMAT=1; shift 1 ;; --help|-h) usage; exit 0 ;; *) echo "Unknown option: $1 (use --help)" >&2; exit 1 ;; esac done # Get JSON content if [[ -n "$JSON_FILE" ]]; then [[ -f "$JSON_FILE" ]] || { echo "File not found: $JSON_FILE" >&2; exit 1; } JSON_STRING=$(cat "$JSON_FILE") elif [[ -z "$JSON_STRING" ]]; then echo "Error: Either --json or --json-file is required" >&2 usage exit 1 fi # Validate JSON if ! echo "$JSON_STRING" | python3 -m json.tool >/dev/null 2>&1; then echo "Error: Invalid JSON" >&2 exit 1 fi # Extract hostname HOSTNAME=$(echo "$JSON_STRING" | grep -oP '"hostname"\s*:\s*"\K[^"]+' || echo "") [[ -n "$HOSTNAME" ]] || { echo "Error: Could not extract hostname from JSON" >&2; exit 1; } # Set output file if not specified if [[ -z "$OUTPUT_FILE" ]]; then OUTPUT_FILE="${SCRIPT_DIR}/credentials/${HOSTNAME}.json" fi # Create credentials directory if needed mkdir -p "$(dirname "$OUTPUT_FILE")" # Create credentials JSON with updateable fields cat > "$OUTPUT_FILE" < "${OUTPUT_FILE}.tmp" && mv "${OUTPUT_FILE}.tmp" "$OUTPUT_FILE" fi echo "Credentials saved to: $OUTPUT_FILE" echo "" echo "To update credentials, use:" echo " bash update_credentials.sh --ctid $(echo "$JSON_STRING" | grep -oP '"ctid"\s*:\s*\K[0-9]+') --credentials-file $OUTPUT_FILE"