#!/bin/bash

set -e  # If any command fails, stop the script immediately

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# Build your Rust program
cargo build --manifest-path "$PROJECT_DIR/Cargo.toml"

# Path to the built binary
spin_path="$PROJECT_DIR/target/debug/tspin"

# Generate shell completions
"$spin_path" --generate-zsh-completions > "$PROJECT_DIR/completions/tspin.zsh"
"$spin_path" --generate-bash-completions > "$PROJECT_DIR/completions/tspin.bash"
"$spin_path" --generate-fish-completions > "$PROJECT_DIR/completions/tspin.fish"

# Inject a do-not-edit header. zsh requires `#compdef` on line 1, so the
# header is inserted after that line; bash and fish get it at the top.
warning="# === DO NOT EDIT — generated by util/generate_shell_completions.sh ==="

inject_after_first_line() {
  local file="$1"
  { head -n 1 "$file"; printf '#\n%s\n#\n' "$warning"; tail -n +2 "$file"; } > "$file.tmp" \
    && mv "$file.tmp" "$file"
}

inject_at_top() {
  local file="$1"
  { printf '%s\n#\n' "$warning"; cat "$file"; } > "$file.tmp" \
    && mv "$file.tmp" "$file"
}

inject_after_first_line "$PROJECT_DIR/completions/tspin.zsh"
inject_at_top          "$PROJECT_DIR/completions/tspin.bash"
inject_at_top          "$PROJECT_DIR/completions/tspin.fish"
