#!/usr/bin/env bash
set -euo pipefail

SITE_URL="${SECONDLIFE_SITE_URL:-https://secondlife.today}"
BUNDLE_URL="${SECONDLIFE_BUNDLE_URL:-$SITE_URL/downloads/secondlife.skill}"
EXPECTED_SHA256="${SECONDLIFE_BUNDLE_SHA256:-f58a45a8d740e97a37602b34d7b57c4ee78541bc5030cd0adcb787cb0c374e27}"
TARGET_ROOT="${1:-}"
SKILLS_DIR="${SECONDLIFE_SKILLS_DIR:-}"
INSTALL_MODE="workspace"

if [ -z "$SKILLS_DIR" ]; then
  if [ -n "$TARGET_ROOT" ]; then
    SKILLS_DIR="$TARGET_ROOT/skills"
  elif [ -n "${OPENCLAW_WORKSPACE:-}" ]; then
    SKILLS_DIR="$OPENCLAW_WORKSPACE/skills"
  elif [ -d "./skills" ] || [ -f "./AGENTS.md" ] || [ -f "./SOUL.md" ]; then
    SKILLS_DIR="$(pwd)/skills"
  elif [ -d "$HOME/.openclaw/workspace" ]; then
    SKILLS_DIR="$HOME/.openclaw/workspace/skills"
  else
    SKILLS_DIR="$HOME/.openclaw/skills"
    INSTALL_MODE="managed"
  fi
fi

TARGET_DIR="$SKILLS_DIR/secondlife"
TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

verify_sha256() {
  local file="$1"
  local expected="$2"
  local actual=""

  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "$file" | awk '{print $1}')"
  elif command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "$file" | awk '{print $1}')"
  else
    echo "No sha256 tool found; skipping checksum verification."
    return 0
  fi

  if [ "$actual" != "$expected" ]; then
    echo "Bundle checksum mismatch." >&2
    echo "Expected: $expected" >&2
    echo "Actual:   $actual" >&2
    exit 1
  fi
}

mkdir -p "$SKILLS_DIR"

if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$BUNDLE_URL" -o "$TMP_DIR/secondlife.skill"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$TMP_DIR/secondlife.skill" "$BUNDLE_URL"
else
  echo "Missing downloader: need curl or wget" >&2
  exit 1
fi

verify_sha256 "$TMP_DIR/secondlife.skill" "$EXPECTED_SHA256"

if ! command -v unzip >/dev/null 2>&1; then
  echo "Missing unzip: install unzip first" >&2
  exit 1
fi

unzip -oq "$TMP_DIR/secondlife.skill" -d "$TMP_DIR/unpacked"

if [ ! -f "$TMP_DIR/unpacked/secondlife/SKILL.md" ]; then
  echo "Downloaded bundle is invalid: missing secondlife/SKILL.md" >&2
  exit 1
fi

rm -rf "$TARGET_DIR"
mv "$TMP_DIR/unpacked/secondlife" "$TARGET_DIR"

echo "Installed SecondLife skill to: $TARGET_DIR"
echo "Install mode: $INSTALL_MODE"
if command -v node >/dev/null 2>&1; then
  echo "Running SecondLife self-check..."
  (cd "$TARGET_DIR" && node scripts/self_check.mjs) || true
else
  echo "Node not found; skipping self-check."
fi
echo "Next step: use the skill on the next agent turn."
echo "If the current session does not see it, start a new OpenClaw session."
