#!/bin/sh
# Install the puz command: one file in ~/.local/bin. Remove it with: rm ~/.local/bin/puz
set -e
case "$(uname -s)" in
  Darwin) OS=macos ;;
  Linux) OS=linux ;;
  MINGW* | MSYS* | CYGWIN*)
    echo "On Windows, install puz from PowerShell instead:"
    echo "  irm https://swords.cx/install.ps1 | iex"
    exit 1 ;;
  *) echo "There is no puz build for $(uname -s). It runs on macOS, Linux and Windows."; exit 1 ;;
esac
case "$(uname -m)" in
  arm64 | aarch64) ARCH=arm64 ;;
  x86_64 | amd64) ARCH=x64 ;;
  *) echo "There is no puz build for $(uname -m) computers."; exit 1 ;;
esac
DIR="${PUZ_BIN:-${SWORDS_BIN:-$HOME/.local/bin}}"
mkdir -p "$DIR"
if ! curl -fsSL "https://swords.cx/cli/puz-$OS-$ARCH" -o "$DIR/puz.new"; then
  rm -f "$DIR/puz.new"
  echo "https://swords.cx has no puz build for $OS-$ARCH yet, or can't be reached."
  exit 1
fi
chmod 755 "$DIR/puz.new"
mv "$DIR/puz.new" "$DIR/puz"
# A green tick on a color terminal, plain text elsewhere. The home folder shows as ~.
SHOWN=$DIR
case "$DIR" in "$HOME"/*) SHOWN="~${DIR#"$HOME"}" ;; esac
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then
  printf '\033[32m✓\033[0m Installed puz in %s\n' "$SHOWN"
else
  echo "Installed puz in $SHOWN"
fi
ON_PATH=yes
case ":$PATH:" in
  *":$DIR:"*) ;;
  *) ON_PATH= ;;
esac
[ -n "$ON_PATH" ] || echo "$DIR is not on your PATH. Add it to run puz by name."
# The old swords command is replaced by puz. Your puzzles and keys stay where they are.
[ ! -e "$DIR/swords" ] || echo "puz replaces the old swords command. You can remove it: rm $SHOWN/swords"

# The first run: puz asks for your name and an optional email. This script comes in on a pipe, so the
# answers are read from the terminal itself. With no terminal (CI, Docker), or with PUZ_NO_SETUP=1
# (or the old SWORDS_NO_SETUP=1), nothing is asked. A setup that fails never fails the install.
ASKED=
if [ -z "${PUZ_NO_SETUP:-}" ] && [ -z "${SWORDS_NO_SETUP:-}" ] && [ -z "${CI:-}" ] && [ -t 1 ] && [ -r /dev/tty ] \
  && (exec </dev/tty) 2>/dev/null; then
  if "$DIR/puz" help setup >/dev/null 2>&1; then
    echo
    "$DIR/puz" setup </dev/tty && ASKED=yes || true
  fi
fi
[ -n "$ASKED" ] || echo "Try it: puz publish hello-world.puz"
