#!/bin/bash
set -euo pipefail

REPO="https://gituwa.lan.theshelf.top/maciek/ffind.git"
# Pin the cloned commit for the script-copy fallback.
# Bump this to a newer commit when you trust it.
PIN="33d94e5"

API_BASE="https://gituwa.lan.theshelf.top/api/v1/repos/maciek/ffind"
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# Get PAT from git credential store (if available)
PAT=$(printf "protocol=https\nhost=gituwa.lan.theshelf.top\n" | git credential fill 2>/dev/null | grep '^password=' | cut -d= -f2- || true)

# --- OS detection ---
detect_os() {
    case "$(uname -s)" in
        Linux*)  echo "linux" ;;
        Darwin*) echo "macos" ;;
        *)       echo "unknown" ;;
    esac
}

# --- Package manager detection ---
detect_pkg_mgr() {
    command -v apt-get >/dev/null 2>&1 && { echo "apt";   return; }
    command -v zypper  >/dev/null 2>&1 && { echo "zypper"; return; }
    command -v dnf     >/dev/null 2>&1 && { echo "dnf";    return; }
    echo "none"
}

OS=$(detect_os)
PM=$(detect_pkg_mgr)
SUDO=""
[ "$(id -u)" -ne 0 ] && SUDO="sudo"

# ffind is a noarch package: one asset per distro family.
asset_suffix() {
    case "$PM" in
        apt)    echo "_all.deb" ;;
        zypper) echo ".noarch.rpm" ;;
        dnf)    echo ".noarch.rpm" ;;
        *)      echo "" ;;
    esac
}

SUFFIX=$(asset_suffix)

install_package() {
    local file="$1"
    case "$PM" in
        apt)
            $SUDO apt-get update
            $SUDO apt-get install -y "$file"
            ;;
        zypper)
            $SUDO zypper install -y --no-gpg-checks --allow-unsigned-rpm "$file"
            ;;
        dnf)
            $SUDO dnf install -y --nogpgcheck "$file"
            ;;
    esac
}

install_deps() {
    case "$PM" in
        apt)
            $SUDO apt-get update
            $SUDO apt-get install -y fzf ripgrep xdg-utils
            ;;
        zypper)
            $SUDO zypper install -y fzf ripgrep xdg-utils
            ;;
        dnf)
            $SUDO dnf install -y fzf ripgrep xdg-utils
            ;;
    esac
}

install_script_copy() {
    # Portable fallback: copy the scripts into ~/.local/bin and the completions
    # into the user's shell dirs. Works on any OS/distro.
    local dest="$HOME/.local/bin"
    mkdir -p "$dest"
    cp "$TMPDIR/repo/ffind" "$dest/ffind"
    cp "$TMPDIR/repo/ffind-preview" "$dest/ffind-preview"
    chmod +x "$dest/ffind" "$dest/ffind-preview"

    mkdir -p "$HOME/.local/share/bash-completion/completions" 2>/dev/null || true
    cp "$TMPDIR/repo/completions/ffind.bash" "$HOME/.local/share/bash-completion/completions/ffind" 2>/dev/null || true

    mkdir -p "$HOME/.local/share/zsh/site-functions" 2>/dev/null || true
    cp "$TMPDIR/repo/completions/_ffind.zsh" "$HOME/.local/share/zsh/site-functions/_ffind" 2>/dev/null || true

    mkdir -p "$HOME/.config/fish/completions" 2>/dev/null || true
    cp "$TMPDIR/repo/completions/ffind.fish" "$HOME/.config/fish/completions/ffind.fish" 2>/dev/null || true

    # Remove the stale fish function from the old installs: it would shadow the
    # new ffind binary inside fish.
    if [ -f "$HOME/.config/fish/functions/ffind.fish" ]; then
        rm -f "$HOME/.config/fish/functions/ffind.fish"
        echo "Removed stale $HOME/.config/fish/functions/ffind.fish (it would shadow the new ffind binary)."
    fi

    echo "ffind installed to $dest. Ensure $dest is on your PATH."
}

clone_pinned() {
    echo "Cloning ffind (pinned at $PIN)..."
    git clone "$REPO" "$TMPDIR/repo"
    git -C "$TMPDIR/repo" checkout "$PIN"
}

if [ "$OS" = "macos" ]; then
    echo "macOS detected: installing via Homebrew + script copy."
    command -v brew >/dev/null 2>&1 || { echo "Error: Homebrew not found (https://brew.sh)" >&2; exit 1; }
    command -v git >/dev/null 2>&1 || { echo "Error: git not found." >&2; exit 1; }
    brew install fzf ripgrep xdg-utils 2>/dev/null || brew install fzf ripgrep
    clone_pinned
    install_script_copy
    echo "ffind installed. Run 'ffind' to search."
    exit 0
fi

if [ "$OS" != "linux" ]; then
    echo "Warning: unsupported OS '$(uname -s)', falling back to script copy." >&2
    command -v git >/dev/null 2>&1 || { echo "Error: git not found." >&2; exit 1; }
    clone_pinned
    install_script_copy
    echo "ffind installed. Run 'ffind' to search."
    exit 0
fi

# --- Linux: prefer the OBS-built native package ---
if [ -n "$SUFFIX" ]; then
    echo "Detected: package manager=$PM"

    if [ -n "$PAT" ]; then
        RELEASE=$(curl -sfH "Authorization: Bearer $PAT" "$API_BASE/releases/latest" 2>/dev/null || true)
        ASSET=$(echo "$RELEASE" | python3 -c "import json,sys; \
                    data=json.load(sys.stdin); \
                    names=[a['name'] for a in data.get('assets',[]) if a['name'].endswith('$SUFFIX') and 'dbgsym' not in a['name'] and '.src.rpm' not in a['name']]; \
                    print(names[0] if names else '')" 2>/dev/null || true)
        URL=$(echo "$RELEASE" | python3 -c "import json,sys; \
                    data=json.load(sys.stdin); \
                    urls=[a['browser_download_url'] for a in data.get('assets',[]) if a['name']=='$ASSET']; \
                    print(urls[0] if urls else '')" 2>/dev/null || true)

        if [ -n "$URL" ] && curl -sfL -H "Authorization: Bearer $PAT" -o "$TMPDIR/$ASSET" "$URL"; then
            echo "Downloaded $ASSET"
            install_package "$TMPDIR/$ASSET"
            echo "ffind installed from OBS package. Run 'ffind' to search."
            exit 0
        fi
    fi

    echo "Warning: no OBS package asset for $PM in the latest release yet." >&2
    echo "(Packages are attached to the release shortly after a tag is pushed; retry in a few minutes.)" >&2
else
    echo "Warning: no native package available for package manager='$PM'." >&2
fi

echo "Falling back to script copy..." >&2

command -v git >/dev/null 2>&1 || { echo "Error: git not found." >&2; exit 1; }

clone_pinned
install_deps
install_script_copy

echo "ffind installed. Run 'ffind' to search."
