#!/bin/sh
# Install murk — https://github.com/iicky/murk
# Usage: curl -fsSL https://raw.githubusercontent.com/iicky/murk/main/install.sh | sh
set -e

REPO="iicky/murk"
INSTALL_DIR="${MURK_INSTALL_DIR:-/usr/local/bin}"

os=$(uname -s)
arch=$(uname -m)

case "$os" in
    Linux)
        case "$arch" in
            x86_64)  target="x86_64-unknown-linux-gnu" ;;
            aarch64) target="aarch64-unknown-linux-gnu" ;;
            armv7*)  target="arm-unknown-linux-gnueabihf" ;;
            *)       echo "error: unsupported architecture: $arch" >&2; exit 1 ;;
        esac
        ;;
    Darwin)
        case "$arch" in
            x86_64)  target="x86_64-apple-darwin" ;;
            arm64)   target="aarch64-apple-darwin" ;;
            *)       echo "error: unsupported architecture: $arch" >&2; exit 1 ;;
        esac
        ;;
    *)
        echo "error: unsupported OS: $os (try cargo install murk-cli)" >&2
        exit 1
        ;;
esac

# Get latest release tag.
tag=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" | grep '"tag_name"' | cut -d'"' -f4)
if [ -z "$tag" ]; then
    echo "error: could not determine latest release" >&2
    exit 1
fi

archive="murk-${tag}-${target}.tar.gz"
url="https://github.com/$REPO/releases/download/$tag/$archive"

echo "installing murk $tag ($target)"

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

curl -fsSL "$url" -o "$tmpdir/$archive"

# Verify checksum.
checksums_url="https://github.com/$REPO/releases/download/$tag/SHA256SUMS"
curl -fsSL "$checksums_url" -o "$tmpdir/SHA256SUMS"
expected=$(grep "$archive" "$tmpdir/SHA256SUMS" | cut -d' ' -f1)
if [ -z "$expected" ]; then
    echo "error: checksum not found for $archive" >&2
    exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
    actual=$(sha256sum "$tmpdir/$archive" | cut -d' ' -f1)
elif command -v shasum >/dev/null 2>&1; then
    actual=$(shasum -a 256 "$tmpdir/$archive" | cut -d' ' -f1)
else
    echo "error: no sha256sum or shasum found — cannot verify download" >&2
    echo "hint: install coreutils or use 'cargo install murk-cli' instead" >&2
    exit 1
fi
if [ "$actual" != "$expected" ]; then
    echo "error: checksum mismatch — expected $expected, got $actual" >&2
    exit 1
fi

# Verify build provenance attestation (optional, requires gh CLI).
if command -v gh >/dev/null 2>&1; then
    if gh attestation verify "$tmpdir/$archive" --repo "$REPO" >/dev/null 2>&1; then
        echo "verified build provenance attestation"
    else
        echo "warning: attestation verification failed — binary may not have been built by CI" >&2
        echo "hint: install the latest gh CLI for attestation support, or verify manually" >&2
    fi
fi

tar xzf "$tmpdir/$archive" -C "$tmpdir"

if [ -w "$INSTALL_DIR" ]; then
    mv "$tmpdir/murk" "$INSTALL_DIR/murk"
else
    sudo mv "$tmpdir/murk" "$INSTALL_DIR/murk"
fi

echo "installed murk to $INSTALL_DIR/murk"
