#!/usr/bin/env bash
# bn.sh - Bana Notes : sync .txt notes to cloud storage via rclone,
# Run: chmod +x bn.sh && ./bn.sh to start

set -euo pipefail

# ==============================================================================
# PROFILE CONFIGURATION
# ==============================================================================
# Default / Primary Profile
PRIMARY_DIR="$HOME/bn"
PRIMARY_REMOTE="bn"

# Alternate Profile (Triggered with the -c flag)
ALT_DIR="$HOME/bn-c"
ALT_REMOTE="bn-c"

# Dynamically set active targets (Defaults to Primary)
CN_DIR="$PRIMARY_DIR"
REMOTE_NAME="$PRIMARY_REMOTE"

# These stay dynamic based on what is active
REMOTE_DIR="$REMOTE_NAME:bn"
DEFAULT_FILE="bn"
# ==============================================================================

CIPHER="aes-256-cbc"
MD_ALGO="sha512"
ENC_EXT="txt.enc"

today() { date +%Y-%m-%d; }

if [ -t 1 ]; then
  RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
  CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
else
  RED=''; GREEN=''; YELLOW=''; CYAN=''; BOLD=''; RESET=''
fi

info() { printf "${CYAN}%s${RESET}\n" "$*"; }
success() { printf "${GREEN}%s${RESET}\n" "$*"; }
warn() { printf "${YELLOW}%s${RESET}\n" "$*"; }
error() { printf "${RED}ERROR: %s${RESET}\n" "$*" >&2; }
die() { error "$*"; exit 1; }

secure_rm() { command -v shred >/dev/null 2>&1 && { shred -u -z "$1" 2>/dev/null || rm -f "$1"; } || rm -f "$1"; }

get_pass() {
  printf "%s" "${1:-Passphrase: }" >&2
  stty -echo; read -r pass; stty echo; echo >&2
  printf '%s' "$pass"
}

encrypt_file() {
  OP_PASS="$3" openssl enc -e -"$CIPHER" -md "$MD_ALGO" -salt -in "$1" -out "$2" -pass env:OP_PASS
  chmod 600 "$2"
}

decrypt_file() {
  OP_PASS="$3" openssl enc -d -"$CIPHER" -md "$MD_ALGO" -in "$1" -out "$2" -pass env:OP_PASS >/dev/null 2>&1
}

check_dependencies() {
  command -v rclone >/dev/null 2>&1 && return 0

  local local_bin
  for local_bin in "$HOME/bin/rclone" "$HOME/.local/bin/rclone"; do
    [ -x "$local_bin" ] && { export PATH="$(dirname "$local_bin"):$PATH"; return 0; }
  done

  warn "rclone is required but was not found on your system."
  printf "Would you like to automatically download the official rclone binary? [Y/n]: "
  read -r ans
  case "$ans" in [nN]) die "rclone is required to sync notes. Aborting." ;; esac
  install_rclone_binary
}

install_rclone_binary() {
  info "Detecting architecture and downloading rclone..."

  local os arch url dest_dir tmp_dir
  os=$(uname | tr '[:upper:]' '[:lower:]')
  arch=$(uname -m)
  [ "$os" = "darwin" ] && os="osx"
  case "$arch" in
    x86_64|amd64) arch="amd64" ;;
    arm64|aarch64) arch="arm64" ;;
    *) die "Unsupported architecture: $arch. Please install rclone manually." ;;
  esac

  if [ -d "$HOME/.local/bin" ]; then dest_dir="$HOME/.local/bin"; else mkdir -p "$HOME/bin"; dest_dir="$HOME/bin"; fi
  url="https://downloads.rclone.org/rclone-current-${os}-${arch}.zip"
  tmp_dir=$(mktemp -d)

  info "Downloading from rclone.org..."
  if curl -sfL "$url" -o "$tmp_dir/rclone.zip"; then
    if command -v unzip >/dev/null 2>&1; then
      unzip -j -q "$tmp_dir/rclone.zip" "*/rclone" -d "$dest_dir" 2>/dev/null || \
      unzip -j -q "$tmp_dir/rclone.zip" "*/rclone.exe" -d "$dest_dir" 2>/dev/null
    else
      rm -rf "$tmp_dir"
      die "The 'unzip' utility is required to extract rclone. Please install unzip or rclone manually."
    fi
    chmod +x "$dest_dir/rclone"
    export PATH="$dest_dir:$PATH"
    success "rclone successfully installed locally to $dest_dir/rclone"
  else
    rm -rf "$tmp_dir"
    die "Download failed. Please check your internet connection or install rclone manually."
  fi
  rm -rf "$tmp_dir"
}

pull_file() {
  local filename="$1"
  rclone copyto "$REMOTE_DIR/$filename" "$CN_DIR/$filename" --update --no-traverse --fast-list >/dev/null 2>&1 || true
}

push_file() {
  local filename="$1"
  [ -f "$CN_DIR/$filename" ] || die "File not found: $CN_DIR/$filename"
  rclone copyto "$CN_DIR/$filename" "$REMOTE_DIR/$filename" --drive-use-trash=false --fast-list
}

bg_push() {
  local filename="$1"
  ( push_file "$filename" >/dev/null 2>&1 || echo "$(date): Background upload failed for $filename" >> "$CN_DIR/.sync_errors" ) &
}

generate_default_help_content() {
  local cmd
  cmd="$(basename "$0")"
  cat << EOF
# Welcome to Bana Notes (${cmd})

Welcome to Bana Notes. (Fun fact: bana means arrow in Sanskrit!) This is your default note file. You can modify, edit, or completely clear this text whenever you want. Below is a quick cheat sheet of all available command options.

## Quick Cheat Sheet

* **${cmd}**
  Open this default scratchpad file (${DEFAULT_FILE}.txt).
* **${cmd} NAME**
  Create or edit a custom plaintext note called 'NAME.txt'.
* **${cmd} -c [command]**
  Switch context to your ALTERNATE cloud storage profile/directory.
  Must be passed first (e.g., '${cmd} -c -l' or '${cmd} -c mynote').

## Core Commands

* **-e NAME**  : Create/edit an encrypted password-protected note (NAME.${ENC_EXT}).
* **-a N1 N2** : Open multiple plaintext notes simultaneously in your editor.
* **-l**       : List all your local notes with file size, type, and modify date.
* **-s TERM**  : Search for a specific keyword or pattern across all plaintext notes.
* **-p**       : Pull all files down from your cloud storage manually.
* **-r**       : Safely rename a file both locally and on your cloud storage.
* **-d**       : Safely delete a file both locally and from your cloud storage.
* **-n**       : Create or open a note named with today's date (YYYY-MM-DD.txt).
* **-b**       : Make a local timestamped backup folder of all current notes.
* **-x**       : Delete the active cloud storage configuration.
* **-c**       : Add alternate cloud storage configuration.
* **-c NOTE**  : Work on NOTE using the alternate cloud storage.
* **-h**       : Display Bana Note help.

Active Backend Configuration:
* rclone Remote: ${REMOTE_NAME}
* Notes Folder : ${CN_DIR}
EOF
}

stage_file() {
  local filename="$1"
  mkdir -p "$CN_DIR"
  local local_path="$CN_DIR/$filename"

  if [ -f "$local_path" ]; then
    local remote_line
    remote_line=$(rclone lsl "$REMOTE_DIR/$filename" 2>/dev/null | head -n1 || true)
    if [ -n "$remote_line" ]; then
      local remote_date remote_time remote_epoch local_epoch
      remote_date=$(echo "$remote_line" | awk '{print $2}')
      remote_time=$(echo "$remote_line" | awk '{print $3}')
      if date -d "$remote_date $remote_time" +%s >/dev/null 2>&1; then
        remote_epoch=$(date -d "$remote_date $remote_time" +%s)
      else
        remote_epoch=$(date -j -f "%Y-%m-%d %H:%M:%S" "$remote_date $remote_time" +%s 2>/dev/null || echo 0)
      fi
      if stat -c %Y "$local_path" >/dev/null 2>&1; then
        local_epoch=$(stat -c %Y "$local_path")
      else
        local_epoch=$(stat -f %m "$local_path")
      fi
      if [ "$remote_epoch" -gt $((local_epoch + 3)) ]; then
        info "Remote $filename is newer – syncing first..."
        rclone copyto "$REMOTE_DIR/$filename" "$local_path" --no-traverse >/dev/null 2>&1
      fi
    fi
  else
    pull_file "$filename"
    if [ ! -f "$local_path" ]; then
      if [ "$filename" = "${DEFAULT_FILE}.txt" ]; then
        generate_default_help_content > "$local_path"
      else
        touch "$local_path"
      fi
    fi
  fi
}

setup_headless() {
  printf "\n${BOLD}Headless authorization${RESET}\n"
  printf "You'll authorize on a different machine that has a web browser,\n"
  printf "then paste the resulting token back here. No SSH tunneling or port forwarding needed.\n\n"
  printf "${BOLD}Which provider are you connecting?${RESET}\n"
  printf " 1) Google Drive\n 2) Microsoft OneDrive\n 3) Dropbox\n 4) Box\n\nSelection [1-4]: "

  local choice provider_type token
  read -r choice
  case "$choice" in
    1) provider_type="drive" ;;
    2) provider_type="onedrive" ;;
    3) provider_type="dropbox" ;;
    4) provider_type="box" ;;
    *) die "Invalid selection. Aborting setup." ;;
  esac

  printf "\n${BOLD}Step 1${RESET}: On a machine with a web browser (with rclone installed), run:\n\n"
  printf " ${BOLD}rclone authorize \"%s\"${RESET}\n\n" "$provider_type"
  printf "It will open a browser tab to authorize access, then print a token block\n"
  printf "like ${BOLD}Paste the following into your remote machine --->${RESET} ... ${BOLD}<---End paste${RESET}\n\n"
  printf "${BOLD}Step 2${RESET}: Copy just the JSON token between those markers and paste it below.\n\n"
  printf "Paste token: "
  read -r token
  [ -n "$token" ] || die "No token provided. Aborting setup."

  if rclone config create "$REMOTE_NAME" "$provider_type" token "$token"; then
    printf "\n"; success "Successfully authenticated and configured '$REMOTE_NAME' backend!"
  else
    printf "\n"; die "Authentication failed. Check that the pasted token is valid and try again."
  fi
  install_self
}

setup() {
  printf "\n${BOLD}Welcome to Bana Notes ($(basename "$0")) Setup!${RESET}\n"
  printf "Let's link your notes folder to your cloud storage backend.\n\n"

  [ -d "$CN_DIR" ] || { mkdir -p "$CN_DIR"; success "Created local notes directory at $CN_DIR"; }

  if rclone listremotes | grep -q "^${REMOTE_NAME}:$"; then
    success "Verified! Found existing cloud connection '$REMOTE_NAME'."
    install_self
    return 0
  fi

  printf "${BOLD}Choose your cloud storage provider for backend '${REMOTE_NAME}':${RESET}\n"
  printf " 1) Google Drive\n 2) Microsoft OneDrive\n 3) Dropbox\n 4) Box\n"
  printf " 5) Advanced (Manual rclone setup)\n 6) Headless (authorize from another machine, no browser here)\n"
  printf "\nSelection [1-6]: "

  local choice provider_type
  read -r choice
  case "$choice" in
    1) provider_type="drive" ;;
    2) provider_type="onedrive" ;;
    3) provider_type="dropbox" ;;
    4) provider_type="box" ;;
    5)
      info "\nLaunching manual rclone setup wizard..."
      printf "CRITICAL: Name your new remote precisely: ${BOLD}%s${RESET}\n\n" "$REMOTE_NAME"
      rclone config
      rclone listremotes | grep -q "^${REMOTE_NAME}:$" || die "Setup incomplete. Could not verify rclone remote '$REMOTE_NAME'."
      install_self
      return 0
      ;;
    6) setup_headless; return 0 ;;
    *) die "Invalid selection. Aborting setup." ;;
  esac

  info "\nInitiating secure authentication with your cloud provider..."
  info "Your web browser should open automatically to authorize Bana Notes."
  printf "Press Enter to launch the authentication page..."
  read -r _

  if rclone config create "$REMOTE_NAME" "$provider_type"; then
    printf "\n"; success "Successfully authenticated and configured '$REMOTE_NAME' backend!"
  else
    printf "\n"; die "Authentication failed or timed out. Please run the script again to retry."
  fi
  install_self
}

install_self() {
  local script_path bin_dir="" d dest
  script_path="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"

  for d in "$HOME/bin" "$HOME/.local/bin"; do
    if [ -d "$d" ] && printf '%s' "$PATH" | grep -q "$d"; then bin_dir="$d"; break; fi
    if [ ! -d "$d" ]; then mkdir -p "$d"; bin_dir="$d"; break; fi
  done

  if [ -z "$bin_dir" ]; then
    warn "Could not find a writable bin directory in PATH."
    printf "\nTo install manually:\n ${BOLD}cp %s ~/bin/$(basename "$0") && chmod +x ~/bin/$(basename "$0")${RESET}\n" "$script_path"
    return
  fi

  dest="$bin_dir/$(basename "$0")"
  cp "$script_path" "$dest"
  chmod +x "$dest"
  success "Installed as $dest"
  printf "You can now run ${BOLD}$(basename "$0")${RESET} from anywhere.\n"

  if ! printf '%s' "$PATH" | grep -q "$bin_dir"; then
    warn "$bin_dir is not in your PATH yet."
    printf "Add this to your shell profile (.bashrc / .zshrc / .profile):\n ${BOLD}export PATH=\"%s:\$PATH\"${RESET}\n" "$bin_dir"
  fi
}

edit_and_push() {
  local filename="${1}.txt"
  stage_file "$filename"
  "${EDITOR:-vi}" "$CN_DIR/$filename"
  bg_push "$filename"
}

cmd_encrypted() {
  local name="$1"
  [ -n "$name" ] || die "Usage: $(basename "$0") [-c] -e NAME"
  name="${name%.txt}"; name="${name%.$ENC_EXT}"
  local filename="${name}.${ENC_EXT}" filepath="$CN_DIR/${name}.${ENC_EXT}"

  mkdir -p "$CN_DIR"
  if [ -f "$filepath" ]; then
    remote_line=$(rclone lsl "$REMOTE_DIR/$filename" 2>/dev/null | head -n1 || true)
    if [ -n "$remote_line" ]; then
      remote_date=$(echo "$remote_line" | awk '{print $2}')
      remote_time=$(echo "$remote_line" | awk '{print $3}')
      if date -d "$remote_date $remote_time" +%s >/dev/null 2>&1; then
        remote_epoch=$(date -d "$remote_date $remote_time" +%s)
      else
        remote_epoch=$(date -j -f "%Y-%m-%d %H:%M:%S" "$remote_date $remote_time" +%s 2>/dev/null || echo 0)
      fi
      if stat -c %Y "$filepath" >/dev/null 2>&1; then
        local_epoch=$(stat -c %Y "$filepath")
      else
        local_epoch=$(stat -f %m "$filepath")
      fi
      if [ "$remote_epoch" -gt $((local_epoch + 3)) ]; then
        info "Remote $filename is newer – syncing first..."
        rclone copyto "$REMOTE_DIR/$filename" "$filepath" --no-traverse >/dev/null 2>&1
      fi
    fi
  else
    rclone copyto "$REMOTE_DIR/$filename" "$filepath" --no-traverse >/dev/null 2>&1 || true
  fi

  local tmp_dir="/tmp"
  [ -d "/run/user/$(id -u 2>/dev/null)" ] && tmp_dir="/run/user/$(id -u)"

  local TMP TMP_ORIG PASS PASS2
  TMP=$(mktemp "$tmp_dir/bn.XXXXXX")
  TMP_ORIG=$(mktemp "$tmp_dir/bn.orig.XXXXXX")
  trap 'secure_rm "$TMP" 2>/dev/null; secure_rm "$TMP_ORIG" 2>/dev/null; unset PASS PASS2 OP_PASS 2>/dev/null; trap - RETURN' RETURN

  if [ -f "$filepath" ]; then
    info "opening $filename"
    PASS=$(get_pass "Passphrase: ")
    decrypt_file "$filepath" "$TMP" "$PASS" || die "bad passphrase or corrupted vault"
  else
    info "creating new encrypted note $filename"
    PASS=$(get_pass "New passphrase: ")
    PASS2=$(get_pass "Confirm passphrase: ")
    [ "$PASS" = "$PASS2" ] || die "passphrases do not match"
    : > "$TMP"
  fi

  cp "$TMP" "$TMP_ORIG"
  "${EDITOR:-vi}" "$TMP"

  if ! cmp -s "$TMP" "$TMP_ORIG"; then
    encrypt_file "$TMP" "$filepath" "$PASS"
    success "saved $filename (mode 600, encrypted)"
    bg_push "$filename"
    info "syncing $filename to $REMOTE_NAME in background..."
  else
    info "no changes"
  fi
}

cmd_multi() {
  local names=("$@")
  [ ${#names[@]} -gt 0 ] || die "Usage: $(basename "$0") [-c] -a NAME1 NAME2 ..."

  local name filename filenames=() filepaths=()
  for name in "${names[@]}"; do
    filename="${name%.txt}.txt"
    stage_file "$filename"
    filenames+=("$filename"); filepaths+=("$CN_DIR/$filename")
  done

  "${EDITOR:-vi}" "${filepaths[@]}"
  for filename in "${filenames[@]}"; do bg_push "$filename"; done
}

resolve_local_ext() {
  [ -f "$CN_DIR/${1}.${ENC_EXT}" ] && printf '%s' "${1}.${ENC_EXT}" || printf '%s' "${1}.txt"
}

cmd_rename() {
  printf "Current filename (without extension): "; read -r old_name
  printf "New filename (without extension): "; read -r new_name

  local old_file new_file
  old_file="$(resolve_local_ext "$old_name")"
  case "$old_file" in
    *".${ENC_EXT}") new_file="${new_name}.${ENC_EXT}" ;;
    *) new_file="${new_name}.txt" ;;
  esac
  local old_path="$CN_DIR/$old_file" new_path="$CN_DIR/$new_file"

  [ -f "$old_path" ] || die "File not found: $old_path"
  [ ! -f "$new_path" ] || die "Target already exists: $new_path"

  cp "$old_path" "$new_path"

  push_file "$new_file" >/dev/null 2>&1 && success "Pushed $new_file to cloud backend"
  if rclone lsf "$REMOTE_DIR/$old_file" >/dev/null 2>&1; then
    rclone deletefile "$REMOTE_DIR/$old_file" && success "Deleted $old_file from cloud backend"
  fi
  rm "$old_path"
  success "Renamed $old_file to $new_file"
}

cmd_delete() {
  printf "Filename to delete (without extension): "; read -r name
  local filename filepath
  filename="$(resolve_local_ext "$name")"
  filepath="$CN_DIR/$filename"

  printf "${RED}Delete %s locally and from cloud storage? [y/N]: ${RESET}" "$filename"
  read -r confirm
  case "$confirm" in [yY]) ;; *) info "Aborted."; exit 0 ;; esac

  if rclone lsf "$REMOTE_DIR/$filename" >/dev/null 2>&1; then
    rclone deletefile "$REMOTE_DIR/$filename" && success "Deleted $filename from cloud storage"
  fi
  if [ -f "$filepath" ]; then
    case "$filename" in *".${ENC_EXT}") secure_rm "$filepath" ;; *) rm "$filepath" ;; esac
    success "Deleted $filepath"
  fi
}

cmd_list() {
  local f name size mtime kind count=0
  shopt -s nullglob
  local files=("$CN_DIR"/*.txt "$CN_DIR"/*."$ENC_EXT")
  shopt -u nullglob

  if [ ${#files[@]} -eq 0 ]; then warn "No notes found in $CN_DIR"; return 0; fi

  printf "${BOLD}%-30s %10s %-16s %s${RESET}\n" "NAME" "SIZE" "MODIFIED" "TYPE"
  for f in "${files[@]}"; do
    name="$(basename "$f")"
    if size=$(stat -f%z "$f" 2>/dev/null); then
      mtime=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$f")
    else
      size=$(stat -c%s "$f")
      mtime=$(stat -c "%y" "$f" | cut -d. -f1)
    fi
    kind="plain"; [[ "$name" == *".$ENC_EXT" ]] && kind="encrypted"
    printf "%-30s %10s %-16s %s\n" "$name" "${size}B" "$mtime" "$kind"
    count=$((count + 1))
  done
  printf "\n%s file(s) in %s\n" "$count" "$CN_DIR"
}

cmd_pull_all() {
  local remote_file name count=0 failed=0
  mkdir -p "$CN_DIR"
  info "Pulling all notes from $REMOTE_NAME..."

  while IFS= read -r remote_file; do
    [ -n "$remote_file" ] || continue
    name="$(basename "$remote_file")"
    if rclone copyto "$REMOTE_DIR/$name" "$CN_DIR/$name"; then
      info "Pulled $name"; count=$((count + 1))
    else
      warn "Failed to pull $name"; failed=$((failed + 1))
    fi
  done < <(rclone lsf "$REMOTE_DIR" 2>/dev/null | grep -E "\.txt$|\.${ENC_EXT}$" || true)

  if [ "$count" -eq 0 ] && [ "$failed" -eq 0 ]; then
    warn "No notes found on $REMOTE_NAME"
  else
    success "Pulled $count file(s) from cloud storage.$( [ "$failed" -gt 0 ] && printf ' %s failed.' "$failed" )"
  fi
}

cmd_search() {
  local term="$1"
  [ -n "$term" ] || die "Usage: $(basename "$0") [-c] -s SEARCHTERM"

  shopt -s nullglob
  local files=("$CN_DIR"/*.txt)
  shopt -u nullglob
  [ ${#files[@]} -eq 0 ] && { warn "No .txt files found in $CN_DIR"; return 0; }

  grep -n -i --color=auto -- "$term" "${files[@]}" 2>/dev/null || info "No matches for \"$term\""
}

cmd_new() { require_setup; edit_and_push "$(today)"; }

cmd_reset() {
  if ! rclone listremotes | grep -q "^${REMOTE_NAME}:$"; then
    info "No existing '$REMOTE_NAME' cloud configuration found. Nothing to reset."
    return 0
  fi

  printf "${RED}This will remove the '%s' cloud storage configuration so you can set it up fresh with a different provider.\n" "$REMOTE_NAME"
  printf "Your local notes in %s will NOT be touched. Continue? [y/N]: ${RESET}" "$CN_DIR"
  read -r confirm
  case "$confirm" in [yY]) ;; *) info "Aborted."; exit 0 ;; esac

  if rclone config delete "$REMOTE_NAME"; then
    success "Removed cloud configuration for '$REMOTE_NAME'."
    info "Run '$(basename "$0")' again to set up a new cloud storage backend."
  else
    die "Failed to remove cloud configuration for '$REMOTE_NAME'."
  fi
}

cmd_backup() {
  local backup_dir="$HOME/bn-$(today)" f count=0
  if [ -d "$backup_dir" ]; then warn "Backup directory already exists: $backup_dir"; else mkdir -p "$backup_dir"; fi

  for f in "$CN_DIR"/*.txt "$CN_DIR"/*."$ENC_EXT"; do
    [ -f "$f" ] || continue
    cp "$f" "$backup_dir/"
    count=$((count + 1))
  done

  if [ "$count" -eq 0 ]; then
    warn "No notes found in $CN_DIR"
    rmdir "$backup_dir" 2>/dev/null || true
  else
    success "Backed up $count file(s) to $backup_dir"
  fi
}

require_setup() {
  if [ ! -d "$CN_DIR" ] || ! grep -q "^\[${REMOTE_NAME}\]" "${RCLONE_CONFIG:-$HOME/.config/rclone/rclone.conf}" 2>/dev/null; then
    if ! rclone listremotes | grep -q "^${REMOTE_NAME}:$"; then
      info "Configuration for profile '${REMOTE_NAME}' missing or incomplete. Initiating setup automatically..."
      setup
    fi
  fi
}

usage() {
  local cmd
  cmd="$(basename "$0")"
  printf "${BOLD}${cmd}${RESET} - Bana Notes Help\n\n"
  printf " ${BOLD}${cmd} [flags]${RESET}          Edit ${DEFAULT_FILE}.txt and push to cloud storage\n"
  printf " ${BOLD}${cmd} [flags] NAME${RESET}     Create/edit NAME.txt and push to cloud storage\n\n"
  printf "${BOLD}Global Profile Flags:${RESET}\n"
  printf " ${BOLD}-c${RESET}                  Switch target to the ALTERNATE cloud profile / directory\n"
  printf "                    (Must be the *first* flag passed, e.g., '${cmd} -c -l' or '${cmd} -c mynote')\n\n"
  printf "${BOLD}Commands:${RESET}\n"
  printf " ${BOLD}-e NAME${RESET}            Create/edit an encrypted note (NAME.%s) and push to cloud storage\n" "$ENC_EXT"
  printf " ${BOLD}-r${RESET}                 Rename a file (locally and on cloud storage - plain or encrypted)\n"
  printf " ${BOLD}-d${RESET}                 Delete a file (locally and on cloud storage - plain or encrypted)\n"
  printf " ${BOLD}-b${RESET}                 Backup notes locally to ~/bn-YYYY-MM-DD\n"
  printf " ${BOLD}-l${RESET}                 List local notes with size, modified date, and type\n"
  printf " ${BOLD}-p${RESET}                 Pull all notes (plain and encrypted) from cloud storage\n"
  printf " ${BOLD}-s TERM${RESET}            Search across plaintext notes for TERM (encrypted notes are skipped)\n"
  printf " ${BOLD}-n${RESET}                 Create/edit a note with today's date\n"
  printf " ${BOLD}-a NAME NAME${RESET}       Open multiple plaintext notes at once\n"
  printf " ${BOLD}-c${RESET}       	         Create alternate cloud storage configuration\n"
  printf " ${BOLD}-c NAME${RESET}            Work on NOTE using alternate cloud storage configuration\n"
  printf " ${BOLD}-x${RESET}                 Reset active cloud storage configuration to set up a different provider\n"
  printf " ${BOLD}-h${RESET}                 Show this help\n\n"
  printf "Active Backend: ${CYAN}rclone Remote: %s${RESET}\n" "$REMOTE_NAME"
  printf "Active Notes Directory: ${CYAN}%s${RESET}\n" "$CN_DIR"
}

main() {
  local script_dir
  script_dir="$(cd "$(dirname "$0")" && pwd)"
  [ -x "$script_dir/rclone" ] && export PATH="$script_dir:$PATH"

  # INTERCEPT PROFILE SWITCH FLAG FIRST
  if [ "${1:-}" = "-c" ]; then
    CN_DIR="$ALT_DIR"
    REMOTE_NAME="$ALT_REMOTE"
    REMOTE_DIR="$REMOTE_NAME:bn"
    DEFAULT_FILE="bn-c"
    shift
  fi

  check_dependencies

  case "${1:-}" in
    -h|--help) usage ;;
    -b|--backup) cmd_backup ;;
    -r|--rename) require_setup; cmd_rename ;;
    -d|--delete) require_setup; cmd_delete ;;
    -l|--list) cmd_list ;;
    -p|--pull-all) require_setup; cmd_pull_all ;;
    -s|--search) shift; cmd_search "${1:-}" ;;
    -n|--new) cmd_new ;;
    -e|--encrypt|--encrypted) require_setup; shift; cmd_encrypted "${1:-}" ;;
    -a|--multi) require_setup; shift; cmd_multi "$@" ;;
    -x|--reset) cmd_reset ;;
    -*) die "Unknown flag: $1. Use -h for help." ;;
    *)
      require_setup
      local name="${1:-$DEFAULT_FILE}"
      edit_and_push "${name%.txt}"
      ;;
  esac
}

main "$@"
