#!/bin/bash
set -e

echo "=== Installing pgvector extension for PostgreSQL ==="

echo "[1/5] Installing build dependencies..."
apk add --no-cache build-base git clang llvm-dev postgresql-dev

echo "[2/5] Cloning pgvector v0.5.1..."
cd /tmp
rm -rf pgvector
git clone --branch v0.5.1 --depth 1 https://github.com/pgvector/pgvector.git

echo "[3/5] Compiling and installing pgvector..."
cd /tmp/pgvector
make
make install

echo "[4/5] Cleaning up build dependencies..."
cd /
rm -rf /tmp/pgvector
apk del build-base git clang llvm-dev postgresql-dev

echo "[5/5] Creating vector extension in database..."
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE EXTENSION IF NOT EXISTS vector;
EOSQL

echo "=== pgvector installation complete ==="
