#!/usr/bin/env bash

set -eu

# Linking the script as the pre-commit hook
SCRIPT_PATH=$(realpath "$0")
HOOK_PATH=$(git rev-parse --git-dir)/hooks/pre-commit
if [ "$(realpath "$HOOK_PATH")" != "$SCRIPT_PATH" ]; then
    read -p "Link this script as the git pre-commit hook to avoid further manual running? (y/N): " answer
    if [[ $answer =~ ^[Yy]$ ]]; then
        ln -sf "$SCRIPT_PATH" "$HOOK_PATH"
    fi
fi

set -x

# Install tools
cargo clippy --version &>/dev/null || rustup component add clippy
cargo shear --version >/dev/null 2>&1 || cargo install --locked cargo-shear
cargo sort --version &>/dev/null || cargo install --locked cargo-sort
cargo sqlx --version &>/dev/null || cargo install --locked sqlx-cli
typos --version &>/dev/null || cargo install --locked typos-cli

rustup toolchain list | grep -q 'nightly' || rustup toolchain install nightly
cargo +nightly fmt --version &>/dev/null || rustup component add rustfmt --toolchain nightly

# Checks
typos .
cargo shear
cargo +nightly fmt -- --check
cargo sort -c

# sqlx 0.9 uses `anonymous` as the default user for local socket URLs.
export PGUSER=${PGUSER:-$USER}
cargo sqlx prepare -- --all-targets --all-features
# `cargo sqlx prepare` uses `cargo check`, which misses query macros compiled only by test harnesses
SQLX_OFFLINE=false SQLX_OFFLINE_DIR=.sqlx cargo test --all-targets --all-features --no-run
git add .sqlx

SQLX_OFFLINE=true cargo test --all-targets
SQLX_OFFLINE=true cargo test --doc
SQLX_OFFLINE=true cargo clippy --all-targets --all-features -- -D warnings
