#!/bin/sh
# ╔══════════════════════════════════════════════════════════════════════════╗
# ║  curlz.sh · wgetz.sh — the domain IS the downloader.                       ║
# ║                                                                            ║
# ║    zsh :  . =(curl{,z.sh})        ·   . =(wget{,z.sh} -qO-)                ║
# ║    pipe:  curl -s curlz.sh | sh   ·   wget -qO- wgetz.sh | sh              ║
# ║                                                                            ║
# ║  POSIX head re-execs into zsh by RE-FETCH (stdin-safe; never $(cat)).      ║
# ╚══════════════════════════════════════════════════════════════════════════╝

# ── re-fetch URL; nginx sub_filter rewrites this to https://$host so the ─────
#    re-exec stays faithful to whichever domain you came from (curlz↔curlz).
BOOT_URL="https://curlz.sh"

_z_fetch() {                                  # print URL body to stdout via whoever exists
    if   command -v curl >/dev/null 2>&1; then curl -fsSL          "$1"
    elif command -v wget >/dev/null 2>&1; then wget -qO-           "$1"
    else printf '%s\n' "need curl or wget on PATH" >&2; exit 1; fi
}

# If we're not already zsh, re-exec into it by RE-FETCHING the body as an
# argument (NOT via stdin — a piped `| sh` would let $(cat)/read steal the
# rest of the script; proven fragile). curl|sh, wget|sh, sh -c "$(...)" all heal here.
if [ -z "${ZSH_VERSION:-}" ]; then
    if command -v zsh >/dev/null 2>&1; then
        exec zsh -c "$(_z_fetch "$BOOT_URL")" "" "$@"
    else
        printf '%s\n' "aurora needs zsh — install it, then re-run." >&2
        exit 1
    fi
fi

# ════════════════════════════════════════════════════════════════════════════
#  From here down: PURE ZSH. We are guaranteed to be running under zsh.
# ════════════════════════════════════════════════════════════════════════════

# ── PHASE 1 · install work, fully isolated. NEVER `exit` (we may be sourced ──
#    via `. =(curl{,z.sh})`). Anonymous function localizes options + locals;
#    `return` ends the function (sourced) OR the script (piped) — safe in both.
() {
    emulate -L zsh
    setopt local_options no_unset pipe_fail extended_glob

    # ── paths & defaults ─────────────────────────────────────────────────────
    local PREFIX=${XDG_CONFIG_HOME:-$HOME/.config}/aurora-motd
    local CACHE_DIR=${XDG_CACHE_HOME:-$HOME/.cache}/aurora-motd
    local ZSHRC=${ZDOTDIR:-$HOME}/.zshrc
    local PAYLOAD=$PREFIX/motd.zsh
    local OS_KIND=linux; [[ $OSTYPE == darwin* ]] && OS_KIND=mac
    local ASSUME_YES=${Z_YES:-0}
    local -a VALID=(synthwave tokyonight catppuccin vapor)
    local DEFAULT_THEME=synthwave
    local THEME=${MOTD_THEME:-$DEFAULT_THEME}

    # canonical boot url (for the payload's own `dot` refresh) + font source
    local CANON=${BOOT_URL:-https://curlz.sh}
    local MAPLE="https://github.com/subframe7536/maple-font/releases/latest/download"
    local FONT_URL=${FONT_URL:-${MAPLE}/$( [[ $OS_KIND == mac ]] \
        && echo MapleMono-NF-unhinted.zip || echo MapleMono-NF.zip )}

    # ── palette + tiny loggers (return, never exit) ──────────────────────────
    local P=$'\e[38;2;245;130;200m' C=$'\e[38;2;130;220;245m' G=$'\e[38;2;150;230;180m'
    local Y=$'\e[38;2;245;210;120m' D=$'\e[38;2;150;140;180m'   B=$'\e[1m' Z=$'\e[0m'
    _say(){ print -r -- "${C}·${Z} $*"; }
    _ok(){  print -r -- "${G}•${Z} $*"; }
    _warn(){ print -r -- "${Y}∗${Z} $*"; }
    _die(){ print -r -- "${P}✗${Z} $*" >&2; return 1; }

    print -r -- "${P}${B}·${Z} ${C}curlz${P}.sh${Z}${D}/${Z}${C}wgetz${P}.sh${Z} ${D}— the domain is the downloader. connecting…${Z}"
    mkdir -p $PREFIX $CACHE_DIR || { _die "cannot create config/cache dirs"; return 1; }

    # which downloader is present (for any extra fetches we make here) ─────────
    local -a GET
    if   (( ${+commands[curl]} )); then GET=(curl -fsSL)
    elif (( ${+commands[wget]} )); then GET=(wget -qO-)
    else _die "need curl or wget"; return 1; fi
    local FGET   # binary fetch-to-file
    (( ${+commands[curl]} )) && FGET=(curl -fL#) || FGET=(wget --show-progress -qO)

    # ── managed-block markers in .zshrc ──────────────────────────────────────
    local MB='# >>> aurora-motd >>>' ME='# <<< aurora-motd <<<'
    _strip(){
        [[ -f $ZSHRC ]] || return 0
        grep -qF "$MB" $ZSHRC || return 0
        local t=$ZSHRC.z.$$
        awk -v b="$MB" -v e="$ME" '$0==b{s=1;next}$0==e{s=0;next}!s' $ZSHRC >$t && mv $t $ZSHRC
    }

    # ── uninstall path ───────────────────────────────────────────────────────
    if [[ -n ${Z_UNINSTALL:-} ]]; then
        [[ -f $ZSHRC ]] && { cp -p $ZSHRC $ZSHRC.z.bak; _strip; }
        rm -rf $PREFIX $CACHE_DIR
        unfunction dot hi 2>/dev/null
        unalias -s sh 2>/dev/null
        _ok "uninstalled. ${D}(fonts kept — remove by hand if you like.)${Z}"
        return 0
    fi

    # ── first-touch theme pick (tty only; stdin may be busy → read /dev/tty) ──
    if (( ! ASSUME_YES )) && [[ -z ${MOTD_THEME:-} && $THEME == $DEFAULT_THEME && -r /dev/tty ]]; then
        print -rn -- "${D}pick a vibe ${Z}(${VALID// /, })${D} — enter for ${B}$THEME${Z}: " >/dev/tty
        local pick; read -r pick </dev/tty; [[ -n $pick ]] && THEME=$pick
    fi
    (( ${VALID[(I)$THEME]} )) || { _warn "unknown '$THEME' → $DEFAULT_THEME"; THEME=$DEFAULT_THEME; }
    _ok "theme: ${B}${THEME}${Z}"

    # ── FONT (Maple Mono NF default) — zip/tar.*/raw ttf|otf/blob ─────────────
    local fdir; [[ $OS_KIND == mac ]] && fdir=$HOME/Library/Fonts || fdir=$HOME/.local/share/fonts
    mkdir -p $fdir
    local tmp=$(mktemp -d) f=$tmp/font.bin
    _say "fetching font ${D}${FONT_URL##*/}${Z}…"
    if "${FGET[@]}" "$f" "$FONT_URL" 2>/dev/null || "${FGET[@]}" "$FONT_URL" "$f" 2>/dev/null; then
        case ${FONT_URL:l} in
            *.zip)          (( ${+commands[unzip]} )) && unzip -qo $f -d $tmp/x ;;
            *.tar.gz|*.tgz) mkdir -p $tmp/x && tar -xzf $f -C $tmp/x ;;
            *.tar.xz)       mkdir -p $tmp/x && tar -xJf $f -C $tmp/x ;;
            *.ttf|*.otf)    mkdir -p $tmp/x && cp $f $tmp/x/${FONT_URL:t} ;;
            *)              mkdir -p $tmp/x && { unzip -qo $f -d $tmp/x 2>/dev/null \
                              || tar -xf $f -C $tmp/x 2>/dev/null || cp $f $tmp/x/font.ttf; } ;;
        esac
        local n=0 ff
        for ff in $tmp/x/**/*.(ttf|otf)(.N); do cp -f $ff $fdir/ && (( n++ )); done
        if (( n )); then
            [[ $OS_KIND == linux ]] && (( ${+commands[fc-cache]} )) && fc-cache -f $fdir >/dev/null 2>&1
            _ok "installed ${B}${n}${Z} font file(s) → ${D}${fdir}${Z}"
            [[ $FONT_URL == *maple* ]] && _say "${D}set your terminal font → ${Z}Maple Mono NF${D}  (other? FONT_URL=your.zip)${Z}"
        else _warn "no fonts found in archive — glyphs may miss"; fi
    else _warn "font download failed; banner still works, glyphs may miss"; fi
    rm -rf $tmp

    # ── write the themed banner payload ──────────────────────────────────────
    _say "installing banner → ${D}${PAYLOAD}${Z}"
    _z_write_payload "$PAYLOAD" || { _die "could not write payload"; return 1; }
    chmod 0644 $PAYLOAD
    _ok "banner written"

    # ── hook .zshrc: source payload + define `dot` (and `hi`) + `.sh` suffix ──
    [[ -f $ZSHRC ]] && cp -p $ZSHRC $ZSHRC.z.bak
    _strip
    cat >> $ZSHRC <<HOOK

$MB  # managed — drive with 'dot', don't hand-edit
export MOTD_THEME="$THEME"
export AURORA_CANON="$CANON"
[[ -o interactive && -r "$PAYLOAD" ]] && source "$PAYLOAD"
$ME
HOOK
    _ok "hooked ${D}${ZSHRC}${Z} · ${B}dot${Z} armed for future shells"

    # ── pre-bake frames for instant first login ──────────────────────────────
    _say "pre-baking frames…"
    env COLUMNS=${COLUMNS:-100} MOTD_THEME=$THEME zsh $PAYLOAD --rebuild >/dev/null 2>&1 \
        && _ok "cache warm" || _warn "self-heals on first login"

    # ── PHASE 2 handoff: arm `dot` + greet in THIS live shell (only when ──────
    #    sourced via `. =(curl{,z.sh})`). Stash resolved values at top level.
    typeset -g _Z_PAYLOAD=$PAYLOAD _Z_ZSHRC=$ZSHRC _Z_CACHE=$CACHE_DIR \
               _Z_THEME=$THEME _Z_VALID="${VALID[*]}" _Z_CANON=$CANON
}

# ── PAYLOAD WRITER ───────────────────────────────────────────────────────────
# Kept as a top-level function so the heredoc body is plain and unindented.
_z_write_payload() {
    cat > "$1" <<'AURORA_MOTD_EOF'
#!/usr/bin/env zsh
# ─────────────────────────────────────────────────────────────────────────────
#  aurora-motd · themed login banner + `dot` controller + `.sh`-as-pipe summon
#  source-safe: emulate -L, locals only, returns (never exits). Sourced from
#  .zshrc on every interactive login; also runnable as `zsh motd.zsh --rebuild`.
# ─────────────────────────────────────────────────────────────────────────────
emulate -L zsh
setopt local_options extended_glob

# honor an opt-out without unsetting the hook
[[ -n ${MOTD_OFF:-} && ${1:-} != --rebuild ]] && return 0

typeset -g AURORA_THEME=${MOTD_THEME:-synthwave}
typeset -g AURORA_FONT=${MOTD_FONT:-maple}
typeset -g AURORA_CANON=${AURORA_CANON:-https://curlz.sh}
local CACHE=${XDG_CACHE_HOME:-$HOME/.cache}/aurora-motd
local CONFIG=${XDG_CONFIG_HOME:-$HOME/.config}/aurora-motd
local ZSHRC=${ZDOTDIR:-$HOME}/.zshrc
mkdir -p $CACHE

# ── theme → palette (truecolor with graceful 256 fallback) ───────────────────
_aurora_palette() {
    local t=$1
    local -gA C
    case $t in
        tokyonight) C=(p $'\e[38;2;122;162;247m' s $'\e[38;2;187;154;247m' a $'\e[38;2;125;207;255m'
                       g $'\e[38;2;158;206;106m' d $'\e[38;2;86;95;137m'   bg fg) ;;
        catppuccin) C=(p $'\e[38;2;245;194;231m' s $'\e[38;2;203;166;247m' a $'\e[38;2;137;220;235m'
                       g $'\e[38;2;166;227;161m' d $'\e[38;2;108;112;134m' bg fg) ;;
        vapor)      C=(p $'\e[38;2;255;113;206m' s $'\e[38;2;185;103;255m' a $'\e[38;2;1;205;254m'
                       g $'\e[38;2;5;255;161m'   d $'\e[38;2;110;100;160m' bg fg) ;;
        *)          C=(p $'\e[38;2;245;130;200m' s $'\e[38;2;180;140;230m' a $'\e[38;2;130;220;245m'
                       g $'\e[38;2;150;230;180m' d $'\e[38;2;150;140;180m' bg fg) ;;  # synthwave
    esac
    C[r]=$'\e[0m'; C[b]=$'\e[1m'
    # crude truecolor probe — fall back to plain if COLORTERM unset
    if [[ -z ${COLORTERM:-} ]]; then local k; for k in p s a g d; do C[$k]=$'\e[36m'; done; fi
}

# ── the particle field (the "dots") ──────────────────────────────────────────
_aurora_field() {
    local cols=${COLUMNS:-80} rows=${1:-5} out="" r c ch
    local -a dots=("·" "˙" "⋆" "∘" " " " " " ")
    for r in {1..$rows}; do
        for c in {1..$cols}; do
            ch=$dots[$(( RANDOM % $#dots + 1 ))]
            [[ $ch == " " ]] && out+=" " || out+="${C[d]}${ch}${C[r]}"
        done
        out+=$'\n'
    done
    print -rn -- "$out"
}

# ── the wordmark ─────────────────────────────────────────────────────────────
_aurora_logo() {
    local host=${1:-curlz.sh}
    print -r -- "${C[b]}${C[p]}  ╭───────────────────────────────╮${C[r]}"
    print -r -- "${C[b]}${C[p]}  │  ${C[a]}aurora${C[s]} · ${C[g]}${(r:18:: :)host}${C[p]}│${C[r]}"
    print -r -- "${C[b]}${C[p]}  ╰───────────────────────────────╯${C[r]}"
}

# ── one-time "dots converge" intro (first summon only) ───────────────────────
_aurora_converge() {
    [[ -t 1 ]] || return 0
    local host=${1:-curlz.sh} cols=${COLUMNS:-80} i mid spread c line
    mid=$(( (cols - ${#host}) / 2 )); (( mid < 0 )) && mid=0
    (( ${+commands[tput]} )) && tput civis
    for i in {1..12}; do
        spread=$(( 12 - i )); line=""
        for c in {1..$cols}; do
            if (( c > mid - spread && c < mid + ${#host} + spread )) && (( RANDOM % 3 == 0 ))
            then line+="${C[d]}·${C[r]}"; else line+=" "; fi
        done
        print -rn -- $'\r'"$line"; sleep 0.018
    done
    print -rn -- $'\r'"${(l:mid:: :)}${C[b]}${C[p]}${host}${C[r]}"; sleep 0.30
    (( ${+commands[tput]} )) && tput cnorm
    print
}

# ── a rotating "fact"/greeting line ──────────────────────────────────────────
_aurora_fact() {
    local -a facts=(
        "the domain is the downloader."
        "rockets land backwards now. so can your shell."
        "from ape to apex: \`. =(curl{,z.sh})\`."
        "the dots are yours. \`dot themes\` for the wardrobe."
        "type a hostname, summon a vibe."
    )
    print -r -- "${C[d]}${facts[$(( (RANDOM % $#facts) + 1 ))]}${C[r]}"
}

# ── render (uses cached frame if fresh, else rebuilds) ───────────────────────
_aurora_render() {
    local frame=$CACHE/frame.$AURORA_THEME
    _aurora_palette $AURORA_THEME
    if [[ ${1:-} == --rebuild || ! -s $frame ]]; then
        { _aurora_logo "${AURORA_HOST:-curlz.sh}"; _aurora_field 3; } >| $frame
    fi
    print
    cat $frame
    _aurora_fact
    print
}

# ── the `dot` controller ─────────────────────────────────────────────────────
dot() {
    emulate -L zsh
    local valid=(synthwave tokyonight catppuccin vapor)
    case ${1:-} in
        ""|greet)  _aurora_render ;;
        themes)    print -r -- "themes: ${valid[*]}   (now: ${AURORA_THEME})" ;;
        .)         # "dot dot" — nuke caches + full rebake + re-greet
                   rm -f $CACHE/frame.* $CACHE/facts 2>/dev/null
                   MOTD_THEME=$AURORA_THEME zsh "${(%):-%x}" --rebuild >/dev/null 2>&1
                   _aurora_render --rebuild ;;
        off)       grep -q '^export MOTD_OFF=1' $ZSHRC 2>/dev/null \
                     || print 'export MOTD_OFF=1' >> $ZSHRC
                   print -r -- "muted for new shells." ;;
        on)        sed -i.bak '/^export MOTD_OFF=1/d' $ZSHRC 2>/dev/null
                   unset MOTD_OFF; print -r -- "unmuted." ;;
        doctor)    print -r -- "theme:   ${AURORA_THEME}"
                   print -r -- "font:    ${AURORA_FONT}"
                   print -r -- "truecolor: ${COLORTERM:-(none — using fallback)}"
                   print -rn -- "nerd-font: "; (( ${+commands[fc-list]} )) \
                       && { fc-list 2>/dev/null | grep -qi 'maple\|nerd' \
                            && print "resolves ✓" || print "not found ✗"; } \
                       || print "(no fc-list)"
                   print -rn -- "suffix .sh: "; alias -s 2>/dev/null | grep -q '^sh=' \
                       && print "armed ✓" || print "off"
                   print -r -- "cache:   ${CACHE}" ;;
        *)         if (( ${valid[(I)$1]} )); then
                       sed -i.bak "s/^export MOTD_THEME=.*/export MOTD_THEME=\"$1\"/" $ZSHRC 2>/dev/null
                       export MOTD_THEME=$1 AURORA_THEME=$1
                       rm -f $CACHE/frame.* 2>/dev/null
                       _aurora_render --rebuild
                   else
                       print -r -- "unknown '$1' — try: dot themes" >&2; return 1
                   fi ;;
    esac
}
alias hi=dot

# ── `.sh`-as-pipe: a bareword hostname summons itself (leashed) ──────────────
_dotz() {
    emulate -L zsh
    setopt local_options pipe_fail
    local word=$1
    if [[ $word == (#i)*(curlz|wgetz).sh || $word == (#i)*(curlz|wgetz).sh/* ]]; then
        local scheme=https; [[ -n ${DOTZ_INSECURE:-} ]] && scheme=http
        print -rP "%F{99}·%f summoning %B${word}%b…"
        if (( ${+commands[curl]} )); then . =(curl -fsSL "${scheme}://${word}")
        else . =(wget -qO- "${scheme}://${word}"); fi
    elif [[ -f $word ]]; then
        zsh "$word" "${@:2}"            # a real local *.sh → run it normally (leash holds)
    else
        print -r -- "no such ritual: $word" >&2; return 127
    fi
}
alias -s sh=_dotz

# ── entrypoint ───────────────────────────────────────────────────────────────
if [[ ${1:-} == --rebuild ]]; then
    _aurora_palette $AURORA_THEME
    _aurora_render --rebuild >/dev/null
else
    # first interactive paint: converge once, then greet
    if [[ -o interactive && ! -f $CACHE/.converged ]]; then
        _aurora_palette $AURORA_THEME
        _aurora_converge "${AURORA_HOST:-curlz.sh}"
        : >| $CACHE/.converged
    fi
    _aurora_render
fi
return 0
AURORA_MOTD_EOF
}

# ── PHASE 2 · TOP LEVEL — runs only when SOURCED (`. =(curl{,z.sh})`). ───────
#    Defines `dot` + greets in the LIVE shell, so the vibe lands instantly.
#    When piped (`curlz.sh | sh` → re-exec zsh -c), there's no persistent shell
#    to arm; the .zshrc hook covers the next login. Both paths are correct.
if [[ -n ${_Z_PAYLOAD:-} && -r ${_Z_PAYLOAD:-/nonexistent} ]]; then
    export MOTD_THEME=${_Z_THEME} AURORA_CANON=${_Z_CANON}
    print -r -- $'\e[38;2;150;230;180m•\e[0m connected. \e[2mthe dots are yours — \e[0mdot\e[2m to re-greet, \e[0mdot themes\e[2m for more.\e[0m'
    source "${_Z_PAYLOAD}"
    unset _Z_PAYLOAD _Z_ZSHRC _Z_CACHE _Z_THEME _Z_VALID _Z_CANON
fi
