#!/bin/sh
# Petfolio installer for macOS and Linux (POSIX sh).
#
#   curl -fsSL https://3ps.online/pets/install.sh | sh -s -- <id>
#   curl -fsSL https://3ps.online/pets/install.sh | sh -s -- <id> --dir ~/some/other/pets
#
# Downloads the companion's zip from https://3ps.online/pets/p/<id>/<id>.zip and unzips it
# into $HOME/.codex/pets/<id>/ (the folder Codex reads; OpenPets reads the same one).
# --dir <path> puts it somewhere else. Needs curl and unzip. Nothing else is touched.
#
# Not affiliated with OpenAI. Codex and ChatGPT are trademarks of OpenAI.

set -eu

BASE="https://3ps.online/pets"
ID=""
DIR=""

usage() {
  echo "usage: curl -fsSL $BASE/install.sh | sh -s -- <id> [--dir <path>]"
  echo "       ids are the last part of a gallery URL, e.g. byte-toad"
}

while [ $# -gt 0 ]; do
  case "$1" in
    --dir) [ $# -ge 2 ] || { echo "--dir needs a path" >&2; exit 2; }; DIR="$2"; shift 2 ;;
    --dir=*) DIR="${1#--dir=}"; shift ;;
    -h|--help) usage; exit 0 ;;
    -*) echo "unknown option: $1" >&2; usage >&2; exit 2 ;;
    *) ID="$1"; shift ;;
  esac
done

[ -n "$ID" ] || { usage >&2; exit 2; }
case "$ID" in
  *[!a-z0-9-]*) echo "bad id: $ID (lowercase letters, digits and dashes only)" >&2; exit 2 ;;
esac

for tool in curl unzip; do
  command -v "$tool" >/dev/null 2>&1 || { echo "$tool is required and was not found on PATH" >&2; exit 1; }
done

[ -n "$DIR" ] || DIR="$HOME/.codex/pets"

TMP="$(mktemp -d 2>/dev/null || mktemp -d -t hatchery)"
trap 'rm -rf "$TMP"' EXIT INT TERM

# Prefer the content-versioned zip URL from gallery.json (Cloudflare caches the bare path
# for hours after a republish). Fall back to the bare path if the manifest is unreachable.
ZIP_PATH="$(curl -fsSL "$BASE/gallery.json" 2>/dev/null | grep -o "p/$ID/$ID\.zip[^\"]*" | head -n 1 || true)"
if [ -z "$ZIP_PATH" ]; then
  ZIP_PATH="p/$ID/$ID.zip"
fi
URL="$BASE/$ZIP_PATH"

echo "downloading $URL"
if ! curl -fsSL "$URL" -o "$TMP/$ID.zip"; then
  echo "download failed. Is '$ID' a published id? See $BASE/gallery.html" >&2
  exit 1
fi

mkdir -p "$DIR"
unzip -oq "$TMP/$ID.zip" -d "$DIR"

if [ ! -f "$DIR/$ID/pet.json" ]; then
  echo "unzip finished but $DIR/$ID/pet.json is missing; the archive layout was not what was expected" >&2
  exit 1
fi

echo "installed $ID -> $DIR/$ID/"
echo "  $(ls "$DIR/$ID" | tr '\n' ' ')"
echo "restart your agent, then pick '$ID' (Codex: Settings > Appearance > Pets, or /pets $ID in the CLI)"
