#!/usr/bin/env bash

# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <https://unlicense.org/>

# notweerdmonk 2026

# ---
# slack-closet — SQLite backed key/value store for Slack data
#
# Tables:
#   - users
#   - channels
#   - messages
#   - message_threads
#
# Key rules:
#   - users: arbitrary text, but not matching channel/message/thread patterns
#   - channels: must start with "#"
#   - messages: must match p1785610939026309
#   - message_threads: must match p1785610939026309:1786025723.220339
#
# Value rules:
#   - users/channels: plain strings
#   - messages/message_threads: JSON text, validated with jq
#
# Commands:
#   init
#   put <key> <value>
#   upsert <table> <key> <value>
#   get <key>
#   get-all <key>
#   del <key>
#   list [all|users|channels|messages|message_threads]
#   search <key_regex> [value_regex]
#
# Notes:
#   - put auto-selects table from key
#   - get auto-searches the matching table
#   - get-all searches all tables
#   - search always searches all tables
#   - added_at stays fixed on first insert
#   - updated_at changes on updates
#
# ---
#
# A word of advice:
#   An LLM wrote this script. It's wise to learn jq and use it to filter the
#   JASON output which this script spews, for acheiving anything productive
#   in the shell. Stay hydrated. Also, pants are not the only bottom wear.
#
# xoxd-ZGF0YWJhc2VzIGFyZSBub3QgYXQgYWxsIGJhc2Vk
#

# Murphy's Law
set -Eeuo pipefail

DB="$(dirname $(realpath ${BASH_SOURCE[0]}))/${DB:-slack-closet-actual.sqlite3}"

check_kv_pairs() {
  [[ -z "$1" ]] && return 255
  [[ "$1" == "--null" || "$1" == "-n" ]] && \
    {
      shift
      [[ $# -eq 0 || "$1" == "" ]] && \
        {
          return 0
        } || \
        {
          return 255
        }
    }

  [[ -z "$1" ]] && return 255
  declare -n keys_to_check="$1"
  shift

  [[ -z "$1" ]] && return 255
  declare -n values_to_check="$1"
  shift

  idx=0
  found=0
  while read -r line
  do
    key="${line%% =*}"
    value="${line##*= }"
    [[
      "$key" == "${keys_to_check[$idx]}" &&
      "$value" == "${values_to_check[$idx]}"
    ]] && \
      ((++idx)) || \
      break
  done <<< "$@"

  [[ $idx -ne ${#keys_to_check[@]} ]] && return 255
  return 0
}

sql_quote() {
  local s="$1"
  s=${s//\'/\'\'} && printf "'%s'" "$s"
}

# seequel-light imples lots of seequels

init_db() {
  local output
  output="$(
  sqlite3 -line "$DB" <<'SQL'
PRAGMA journal_mode=WAL;

CREATE TABLE IF NOT EXISTS users (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
  updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);

SELECT EXISTS (
    SELECT 1 FROM sqlite_schema
    WHERE type = 'table' AND name = 'users'
) AS users_table_exists;

CREATE TABLE IF NOT EXISTS channels (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
  updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);

SELECT EXISTS (
    SELECT 1 FROM sqlite_schema
    WHERE type = 'table' AND name = 'channels'
) AS channels_table_exists;

CREATE TABLE IF NOT EXISTS messages (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
  updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);

SELECT EXISTS (
    SELECT 1 FROM sqlite_schema
    WHERE type = 'table' AND name = 'messages'
) AS messages_table_exists;

CREATE TABLE IF NOT EXISTS message_threads (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
  updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);

SELECT EXISTS (
    SELECT 1 FROM sqlite_schema
    WHERE type = 'table' AND name = 'message_threads'
) AS message_threads_table_exists;

SQL
)"

  declare -a keys=(
    'journal_mode'
    'users_table_exists'
    'channels_table_exists'
    'messages_table_exists'
    'message_threads_table_exists'
  )
  declare -a values=(
    'wal'
    1
    1
    1
    1
  )
  check_kv_pairs keys values "$output"
}

# organization multiplies productivity

table_for_key() {
  local key="$1"
  if [[ "$key" =~ ^#.+$ ]]; then
    echo channels
  elif [[ "$key" =~ ^p[0-9]+:[0-9]+\.[0-9]+$ ]]; then
    echo message_threads
  elif [[ "$key" =~ ^p[0-9]+$ ]]; then
    echo messages
  else
    echo users
  fi
}

validate_key_for_table() {
  local table="$1" key="$2"
  case "$table" in
    users) [[ "$key" != \#* && "$key" != p* ]] ;;
    channels) [[ "$key" =~ ^#.+$ ]] ;;
    messages) [[ "$key" =~ ^p[0-9]+$ ]] ;;
    message_threads) [[ "$key" =~ ^p[0-9]+:[0-9]+\.[0-9]+$ ]] ;;
    *) return 1 ;;
  esac
}

validate_json_if_needed() {
  local table="$1" value="$2"
  case "$table" in
    messages|message_threads)
      command -v jq >/dev/null 2>&1 || { echo "jq is required for JSON validation" >&2; exit 1; }
      printf '%s' "$value" | jq -e . >/dev/null
      ;;
  esac
}

# seequel beach

upsert_kv() {
  local table="$1" key="$2" value="$3"

  validate_key_for_table "$table" "$key" || { echo "invalid key for $table: $key" >&2; exit 1; }
  validate_json_if_needed "$table" "$value"

  local output
  output="$(sqlite3 -line "$DB" <<SQL
INSERT INTO $table (key, value)
VALUES ($(sql_quote "$key"), $(sql_quote "$value"))
ON CONFLICT(key) DO UPDATE SET
  value = excluded.value,
  updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now');

SELECT key,value
FROM $table
WHERE key = $(sql_quote "$key");
SQL
)"

  declare -a keys=('key' 'value') 
  declare -a values=($key $value)

  check_kv_pairs keys values "$output"
}

# seequel again

get_one() {
  local table="$1" key="$2"
  sqlite3 -json "$DB" <<SQL
SELECT '$table' AS table_name, key, value, added_at, updated_at
FROM $table
WHERE key = $(sql_quote "$key");
SQL
}

get_all() {
  local key="$1"
  sqlite3 -json "$DB" <<SQL
SELECT 'users' AS table_name, key, value, added_at, updated_at FROM users WHERE key = $(sql_quote "$key")
UNION ALL
SELECT 'channels' AS table_name, key, value, added_at, updated_at FROM channels WHERE key = $(sql_quote "$key")
UNION ALL
SELECT 'messages' AS table_name, key, value, added_at, updated_at FROM messages WHERE key = $(sql_quote "$key")
UNION ALL
SELECT 'message_threads' AS table_name, key, value, added_at, updated_at FROM message_threads WHERE key = $(sql_quote "$key");
SQL
}

del_kv() {
  local table="$1" key="$2"

  key=$(sql_quote "$key")

  local output
  output="$(sqlite3 -line "$DB" <<SQL
DELETE FROM $table WHERE key = $key;

SELECT key,value
FROM $table
WHERE key = $key;
SQL
)"
  
  check_kv_pairs --null "$output"
}

# moar seequels

list_table() {
  local table="$1"
  sqlite3 -json "$DB" <<SQL
SELECT '$table' AS table_name, key, value, added_at, updated_at
FROM $table
ORDER BY key;
SQL
}

list_all() {
  sqlite3 -json "$DB" <<'SQL'
SELECT 'users' AS table_name, key, value, added_at, updated_at FROM users
UNION ALL
SELECT 'channels' AS table_name, key, value, added_at, updated_at FROM channels
UNION ALL
SELECT 'messages' AS table_name, key, value, added_at, updated_at FROM messages
UNION ALL
SELECT 'message_threads' AS table_name, key, value, added_at, updated_at FROM message_threads
ORDER BY table_name, key;
SQL
}

search_all() {
  local key_regex="$1" value_regex="${2:-}"
  if [[ -n "${value_regex:-}" ]]; then
    sqlite3 -json "$DB" <<'SQL' | jq -c --arg re "$key_regex" --arg vre "$value_regex" '
      [ .[] | select(.key | test($re)) | select(.value | test($vre)) ]
    '
SELECT 'users' AS table_name, key, value, added_at, updated_at FROM users
UNION ALL
SELECT 'channels' AS table_name, key, value, added_at, updated_at FROM channels
UNION ALL
SELECT 'messages' AS table_name, key, value, added_at, updated_at FROM messages
UNION ALL
SELECT 'message_threads' AS table_name, key, value, added_at, updated_at FROM message_threads;
SQL
  else
    sqlite3 -json "$DB" <<'SQL' | jq -c --arg re "$key_regex" '
      [ .[] | select(.key | test($re)) ]
    '
SELECT 'users' AS table_name, key, value, added_at, updated_at FROM users
UNION ALL
SELECT 'channels' AS table_name, key, value, added_at, updated_at FROM channels
UNION ALL
SELECT 'messages' AS table_name, key, value, added_at, updated_at FROM messages
UNION ALL
SELECT 'message_threads' AS table_name, key, value, added_at, updated_at FROM message_threads;
SQL
  fi
}

# finally some shell scripting

usage() {
  sed -n '/^# ---$/,/^# ---$/p' "$0" | sed '/^# ---$/d' | sed 's/^# \{0,1\}//'
}

# check for dependencies
check_dep_tool() {
  [[ -z "$1" ]] && return 255
  if ! command -v "$1" >/dev/null 2>&1;
  then
    printf "%s: required tool '%s' was not found" \
      "$scriptname" "$1" >&2
    [[ $# -gt 1 && -n "$2" ]] && printf "; %s\n" "$2" >&2 || echo
    exit 1
  fi
}

check_action() {
  [[ ! -v action || -z "$action" ]] && echo get || echo "$action"
  return 0
}

check_key() {
  [[ ! -v key || -z "$key" ]] && echo "Key not provided" >&2 && exit 1
  return 0
}

check_type() {
  [[ -v type && -n "$type" ]] && \
    echo "$type" || \
    {
      check_key
      echo "$(table_for_key "$key")"
    }
}

check_value() {
  [[ ! -v value || -z "$value" ]] && echo "Value not provided" >&2 && exit 1
  return 0
}

check_args() {
  case "$@" in
    key)
      check_key
      echo "$key"
      ;;
    type)
      check_type
      ;;
    all)
      ;&
      *)
      local type
      type="$(check_type)"
      local status=$?
      [[ $status -ne 0 ]] && exit 1
      check_value
      echo "$type"
      ;;
  esac
}

main() {
  check_dep_tool "jq"

  action="$(check_action)"

  local output
  case "$action" in
    init)
      init_db
      ;;
    put)
      ;&
    upsert)
      type="$(check_args)"
      upsert_kv "$type" "$key" "$value"
      ;;
    get)
      type="$(check_args "type")"
      output="$(get_one "$type" "$key")"
      ;;
    get-all)
      key="$(check_args "key")"
      output="$(get_all "$key")"
      ;;
    del)
      type="$(check_args "type")"
      del_kv "$type" "$key"
      ;;
    list)
      case "${type:-all}" in
        all) list_all ;;
        users|channels|messages|threads) list_table "$type" ;;
        *) echo "Invalid table: $type" >&2; exit 1 ;;
      esac
      ;;
    search)
      check_key
      output="$(search_all "$key" "${value:-}")"
      ;;
    *)
      usage
      exit 1
      ;;
  esac

  # yay jq, atleast more than what can be found on YouTube
  [[ -v output && -n "$output" ]] && \
    {
      [[ -v json && $json -ne 0 ]] && \
        jq -r . <<< "$output" || \
        echo "$output" | jq -r \
          '.[]
          | (.updated_at
          | strptime("%Y-%m-%dT%H:%M:%S%Z")
          | strftime("%a, %d %b %Y %H:%M:%S %Z")) as $modified
          | "Modified\t\($modified)\nType\t\t\(.table_name)\n\(.key)\t\(.value)"'
    }
}

# proper bash things

source icebarg.bash

# resolve the script's filename and directory.
scriptname="$(basename "${BASH_SOURCE[0]}")"
scriptdir="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"

# description of the script
scriptdesc="SQLite backed key/value store for Slack data"

# define the command-line options and their argument requirements.
optstring_input=\
"type:arg,"\
"key:arg,"\
"value:arg,"\
"json:noarg,"\
"help:noarg"

# convert option definitions into the format used by getopt.
optstring="$(make_optstring "$optstring_input")"

# define the help text for each option and create the optdesc array.
optdesc_input=\
"type:arg:Type of key [users|channel|messages|threads],"\
"key:arg:Key to store,"\
"value:arg:Value associated with key,"\
"json:noarg:Output as JSON,"\
"help:noarg:Display this message"

eval "$(make_optsdesc $optdesc_input)"

if opts="$(parse_opts "$optstring" "$@")"
then
  eval set -- "$opts"
else
  [[ $# -eq 0 ]] && usage
  exit 1
fi

# assign option values to variables.
[[ -n "$1" && ! "$1" =~ ^-{1,2}.*$ ]] && \
  {
    action="$1"
    shift
  }
while true; do
  case "$1" in
    -t|--type)
      type="$2"
      shift 2
      ;;
    -k|--key)
      shift
      key=""
      # allow a key to span multiple command-line words until another option.
      while [[ ! "$1" =~ ^-{1,2}[^-]*$ ]]
      do
        [[ -n "$key" ]] && key+=" "
        key+="$1"
        shift
      done
      ;;
    -v|--value)
      shift
      value=""
      # allow a value name to span multiple command-line words.
      while [[ ! "$1" =~ ^-{1,2}[^-]*$ ]]
      do
        [[ -n "$value" ]] && value+=" "
        value+="$1"
        shift
      done
      ;;
    -j|--json)
      json=1
      shift
      ;;
    -h|--help)
      print_usage "$scriptname" "$scriptdesc" optdesc
      exit
      ;;
    --)
      # end of options; discard the marker and leave the parsing loop.
      shift
      break
      ;;
    *)
      # no more recognized options.
      break
      ;;
  esac
done

# everybody loves C so much

main "$@"
