#!/usr/bin/env bash

: <<'DOC'
API for managing persistent shell rc files.

Provides helpers to detect the user's shell rc file, check for existing
lines, append new lines (with or without interactive confirmation).
DOC

function __shell_rc__path() {
  case "$(basename "${SHELL:-}")" in
    bash) echo "$HOME/.bashrc" ;;
    zsh) echo "$HOME/.zshrc" ;;
    *)
      return 1
      ;;
  esac
}

function __shell_rc__has_line() {
  local file="$1"
  local line="$2"

  [[ -f "$file" ]] && grep -Fqx "$line" "$file"
}

function __shell_rc__is_interactive() {
  [[ -t 0 ]]
}

: <<'DOC'
Offer to append a line to the user's shell rc file.

In interactive shells, prompts for confirmation. In non-interactive shells
or unsupported shells, prints a warning with the line to add manually.
Idempotent: skips if the line already exists.
DOC
function shell_rc_offer_line() {
  local description="$1"
  local line="$2"
  local rc_file

  rc_file="$(__shell_rc__path)" || {
    warn "Add $description to your shell rc manually:"
    warn "  $line"
    return 0
  }

  if __shell_rc__has_line "$rc_file" "$line"; then
    return 0
  fi

  if ! __shell_rc__is_interactive; then
    warn "Add $description to $rc_file:"
    warn "  $line"
    return 0
  fi

  local reply
  read -r -p "Add $description to $rc_file now? [y/N] " reply
  if [[ ! "$reply" =~ ^[Yy]$ ]]; then
    warn "Add $description to $rc_file:"
    warn "  $line"
    return 0
  fi

  touch "$rc_file"
  if [[ -s "$rc_file" ]]; then
    printf '\n%s\n' "$line" >> "$rc_file"
  else
    printf '%s\n' "$line" >> "$rc_file"
  fi

  log "  Added $description to $rc_file"
}

: <<'DOC'
Append a line to the user's shell rc file without prompting.

Use this when intent has already been declared (e.g. via ops.lock postinstall)
and interactive confirmation would be redundant.
Idempotent: skips if the line already exists.
DOC
function shell_rc_add_line() {
  local description="$1"
  local line="$2"
  local rc_file

  rc_file="$(__shell_rc__path)" || {
    warn "Add $description to your shell rc manually:"
    warn "  $line"
    return 0
  }

  if __shell_rc__has_line "$rc_file" "$line"; then
    return 0
  fi

  touch "$rc_file"
  if [[ -s "$rc_file" ]]; then
    printf '\n%s\n' "$line" >> "$rc_file"
  else
    printf '%s\n' "$line" >> "$rc_file"
  fi

  log "  Added $description to $rc_file"
}
