#!/bin/sh
set -e

g="\033[38;2;255;200;0m"
y="\033[38;2;160;174;188m"
r="\033[0m"
printf "%b\n" \
  "" \
  "${g}      ⢀⣄${r}" \
  "${g}  ⠘⣷⣦⣠⣿⣿⣧⣠⣶⡟${r}" \
  "${g}   ⢿⣿⣿⣿⣿⣿⣿⣿⠃${r}" \
  "${g}   ⠘⠛⠛⠛⠛⠛⠛⠛${r}" \
  "${g}   ⠈⠉⠉⠉⠉⠉⠉⠉${r}" \
  "" \
  "    ${g}rais${y}.sh${r}" \
  ""

# Detect OS
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$OS" in
  darwin) OS="darwin" ;;
  linux)  OS="linux" ;;
  *)      printf "%b\n" "${y}error: unsupported OS: ${g}%s${r}" "$OS" >&2; exit 1 ;;
esac

# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
  x86_64|amd64)   ARCH="amd64" ;;
  aarch64|arm64)   ARCH="arm64" ;;
  armv7*)          ARCH="armv7" ;;
  *)               printf "%b\n" "${y}error: unsupported architecture: ${g}%s${r}" "$ARCH" >&2; exit 1 ;;
esac

# Determine destination binary path
DEST="${RAIS_BINARY_DESTINATION:-$HOME/.local/bin/rais}"
case "$DEST" in
  */) printf "%b\n" "${y}error: RAIS_BINARY_DESTINATION must not end in /${r}" >&2; exit 1 ;;
esac
DEST_DIR="$(dirname "$DEST")"
mkdir -p "$DEST_DIR"

# Detect download tool
if command -v curl >/dev/null 2>&1; then
  DOWNLOADER="curl"
elif command -v wget >/dev/null 2>&1; then
  DOWNLOADER="wget"
else
  printf "%b\n" "${y}error: curl or wget is required${r}" >&2; exit 1
fi

printf "%b\n" "${y}1. installing ${g}rais${y} for ${g}${OS}${y}/${g}${ARCH}${y}...${r}"
printf "%b\n" "${y}2. downloading now...${r}"

# Download and extract
TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"' EXIT
if [ "$DOWNLOADER" = "curl" ]; then
  curl --progress-bar --fail -L \
    -H "X-Rais-Version: 0.0.0" \
    -H "X-Rais-OS: $OS" \
    -H "X-Rais-Arch: $ARCH" \
    "https://update.rais.sh/" -o "$TMPFILE"
else
  wget --progress=bar -q -O "$TMPFILE" \
    --header="X-Rais-Version: 0.0.0" \
    --header="X-Rais-OS: $OS" \
    --header="X-Rais-Arch: $ARCH" \
    "https://update.rais.sh/"
fi

gunzip -c "$TMPFILE" > "$DEST" || { printf "%b\n" "${y}error: failed to decompress binary${r}" >&2; exit 1; }
chmod +x "$DEST"

# Get version (binary prints to stderr and may exit non-zero)
VER=$("$DEST" --version 2>&1 || true)
if [ -z "$VER" ]; then
  printf "%b\n" "${y}error: failed to get version from binary${r}" >&2; exit 1
fi

printf "%b\n" "${y}3. installed ${g}rais${y} (${g}${VER}${y})${r}"

# Check if destination dir is in PATH
case ":$PATH:" in
  *":$DEST_DIR:"*) ;;
  *)
    printf "%b\n" "${y}4. warning: please add ${g}${DEST_DIR}${y} to your PATH${r}"
    ;;
esac
