#Dependencies: coreutils, md5sum (or md5 on macOS), ImageMagick (for -f png)
usage() {
cat <<USAGE
Usage: $0 -n "Full Name" [-s size] [-l initials_len] [-o outfile] [-b border_px] [-p palette] [-f format]
-n name Name or initials (use '-' to read from stdin)
-s size Size in px (default 128)
-l len Number of initials (1 or 2, default 2)
-o outfile Output filename, use '-' for stdout (default avatar.svg)
-b border Border stroke width in px (default 0 = no stroke)
-p palette Use preset palette (1) or deterministic hex (0). Default 1
-f format svg or png (default svg). PNG requires ImageMagick 'convert'
-h Show this help
#Examples:
#$0 -n "Rick B" -s 128 -o rick.svg
$0 -n "Rick B" -s 256 -b 6 -p 1 -f png -o rick.png
echo "Rick B" | $0 -s 128 -f svg -o -
USAGE
exit 1
}

#Defaults
NAME=""
SIZE=128
LEN=2
OUT="avatar.svg"
BORDER=0
PALETTE=1
FORMAT="svg"

#Parse args
while getopts "n:s:l:o:b:p:f:h" opt; do
case $opt in
n) NAME="$OPTARG" ;;
s) SIZE="$OPTARG" ;;
l) LEN="$OPTARG" ;;
o) OUT="$OPTARG" ;;
b) BORDER="$OPTARG" ;;
p) PALETTE="$OPTARG" ;;
f) FORMAT="$OPTARG" ;;
*) usage ;;
esac
done

#If name is '-', read from stdin
if [ -z "$NAME"] || [ "$NAME" = "-"]; then
    if [ -t 0] && [ "$NAME" != "-"]; then
    usage
    fi
NAME="$(cat - | tr -d '\r\n' | sed 's/^[[:space:]]//;s/[[:space:]]$//')"
fi
[ -n "$NAME"] || usage

#Helpers for md5 cross-platform
md5hex() {
if command -v md5sum >/dev/null 2>&1; then
echo -n "$1" | md5sum | awk '{print $1}'
else
# macOS md5
echo -n "$1" | md5
fi
}

#Simple palette (pleasant colors) - expand if you want more
PALETTE_COLORS=(
"1abc9c" "2ecc71" "3498db" "9b59b6" "34495e"
"16a085" "27ae60" "2980b9" "8e44ad" "2c3e50"
"f39c12" "d35400" "c0392b" "e67e22" "e74c3c"
)

#Choose background color: palette mode or md5->hex
choose_color() {
local key="$1"
if [ "$PALETTE" -ne 0]; then
local h
h="$(md5hex "$key")"
# take first 8 bits to pick index
local idx_hex="${h:0:2}"
local idx=$((0x$idx_hex % ${#PALETTE_COLORS[@]}))
echo "#${PALETTE_COLORS[$idx]}"
else
echo "#${$(md5hex "$key")}" 2>/dev/null || echo "#$(md5hex "$key" | cut -c1-6)"
fi
}

#Compute initials (basic, handles ASCII and many UTF-8 cases)
compute_initials() {
local nm="$1"
local len="$2"

#split on whitespace, preserve unicode words using awk
#get first and last word
IFS=$'\n' read -r -d '' -a words < <(awk '{
n=split($0,a,/([[:space:]]+)/);
out="";
for(i=1;i<=n;i++){ if(a[i] ~ /[^[:space:]]/) {print a[i]} }
}' <<<"$nm" && printf '\0')
if [ "${#words[@]}" -eq 0]; then
echo "?"
return
fi
if [ "$len" -eq 1]; then
# first grapheme: use first byte; this is a best-effort approach
printf "%s" "${words:0:1}" | awk '{print toupper($0)}'
else
if [ "${#words[@]}" -ge 2]; then
# take first char of first and last
a="${words}"
b="${words[-1]}"
# take first UTF-8 character (best-effort)
a1="$(printf "%s" "$a" | sed -E 's/^(.).*/\1/')" || a1="${a:0:1}"
b1="$(printf "%s" "$b" | sed -E 's/^(.).*/\1/')" || b1="${b:0:1}"
printf "%s%s" "$a1" "$b1" | awk '{print toupper($0)}'
else
# single word: take first two chars
printf "%s" "${words:0:2}" | awk '{print toupper($0)}'
fi
fi
}

#Generate values
INITIALS="$(compute_initials "$NAME" "$LEN")"
BG_COLOR="$(choose_color "$NAME")"
FG_COLOR="#ffffff"
FONT_FAMILY="Helvetica,Arial,sans-serif"

#Font size scaled to size: use ~0.44 * SIZE for two letters, larger for one
if [ "$LEN" -eq 1]; then
FONT_SIZE=$(( SIZE * 55 / 100 ))
else
FONT_SIZE=$(( SIZE * 44 / 100 ))
fi

CX=$(( SIZE / 2 ))
CY=$(( SIZE / 2 ))
R=$(( SIZE / 2 ))

#Create SVG content (with optional stroke for border)
svg_content() {
cat <<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="$SIZE" height="$SIZE" viewBox="0 0 $SIZE $SIZE">
<defs>
<style>
text { font-family: $FONT_FAMILY; font-weight:700; }
</style>
</defs>
<circle cx="$CX" cy="$CY" r="$R" fill="$BG_COLOR"/>
$( if [ "$BORDER" -gt 0]; then
# stroke should be inside; use stroke-width and r adjusted if desired
echo " <circle cx="$CX" cy="$CY" r="$R" fill="none" stroke="#ffffff" stroke-width="$BORDER" opacity="1" />"
fi )
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="$FG_COLOR" font-size="$FONT_SIZE">${INITIALS}</text>
</svg>
SVG
}

#Output handling
if [ "$FORMAT" = "svg"]; then
if [ "$OUT" = "-"]; then
svg_content
else
svg_content > "$OUT"
fi
exit 0
elif [ "$FORMAT" = "png"]; then
if ! command -v convert >/dev/null 2>&1; then
echo "ImageMagick 'convert' required for PNG output. Install via 'brew install imagemagick' or your package manager." >&2
exit 2
fi

#create SVG in temp, convert to PNG
tmp_svg="$(mktemp --suffix=.svg 2>/dev/null || mktemp /tmp/avatarXXXXXX.svg)"
tmp_png="$(mktemp --suffix=.png 2>/dev/null || mktemp /tmp/avatarXXXXXX.png)"
svg_content > "$tmp_svg"

#use convert to rasterize at exact size and preserve transparency
convert -background none "$tmp_svg" -resize "${SIZE}x${SIZE}" "$tmp_png"
if [ "$OUT" = "-"]; then
cat "$tmp_png"
else
mv "$tmp_png" "$OUT"
fi
rm -f "$tmp_svg" 2>/dev/null || true
exit 0
else
echo "Unknown format: $FORMAT" >&2
usage
fi
