blob: 725cf21ffc7ee31e658a24c8322754a317889223 (
plain) (
tree)
|
|
#!/usr/bin/env bash
# Gab es un cliente alternativo al programa de chat en colorfield.space
# Reemplace la variable $GAB_FILE con la ruta a su historial de chat
# Se asume que cada línea de chat comienza con: "user_name >"
# # # # # #->
HELP_TEXT=$(
cat <<EOF
GAB - Una simple interfaz de chat
syntax: gab [bandera] [valor]
bandera valor
---------- ---------------
-h, --help ninguno
-m, --msg Mensaje entre comillas a enviar al chat\n
-l, --log Un número entero con la cantidad de filas que quieres ver, por defecto 5
EOF
)
set -o errexit
set -o errtrace
set -o pipefail
GAB_DEBUG=0
[[ $GAB_DEBUG -eq 0 ]] && GAB_LOG=/var/gab/chatlog.txt || GAB_LOG="$HOME/chatlog.txt"
TITLE="GAB v1.4 'Haga click aquí para ingresar mensaje'"
LAST_MSG_DATE=$(date -r $(stat -f %m $GAB_LOG))
SEPARATOR='>'
color_red='\033[31m'
term_reset='\033[0m'
term_bold='\033[1m'
term_dim='\033[2m'
term_italic='\033[3m'
term_reverse='\033[7m'
# Muestra un mensaje de error (se puede pasar por parámetro opcionalmente)
error() {
local msg=${1:-'Ha ocurrido un error'.}
echo -e "${term_bold}${color_red}ERROR: ${term_reset}${msg}" >&2
}
# Imprime un mensaje y termina la ejecución del script devolviendo un nro de
# error, por defecto -1
#Parámetros: mensaje y nro de error
die() {
error $1
exit ${2:-1}
}
# Muestra un mensaje al usuario y termina el programa en paz
info() {
echo $1
exit 0
}
# chequeamos si se puede escribir en el chatlog
if [[ ! -w $GAB_LOG ]]; then
die "No es posible escribir en $GAB_LOG" 1
fi
# https://github.com/dylanaraps/pure-sh-bible#trim-leading-and-trailing-white-space-from-string
trim_string() {
# Usage: trim_string " example string "
# Remove all leading white-space.
# '${1%%[![:space:]]*}': Strip everything but leading white-space.
# '${1#${XXX}}': Remove the white-space from the start of the string.
trim=${1#${1%%[![:space:]]*}}
# Remove all trailing white-space.
# '${trim##*[![:space:]]}': Strip everything but trailing white-space.
# '${trim%${XXX}}': Remove the white-space from the end of the string.
trim=${trim%${trim##*[![:space:]]}}
printf '%s\n' "$trim"
}
EXCLAMATIONS=('dice'
'exclama'
'declara'
'filosofa'
'pontifica'
'insinúa'
'susurra'
'publica'
'grita'
'manifiesta'
'expone'
'anuncia'
'denuncia'
'observa'
'recita'
'chamuya'
'pronuncia'
'parlotea'
)
# Usage: random_array_element "array"
random_array_element() {
local arr=("$@")
printf '%s\n' "${arr[RANDOM % $#]}"
}
choose_exclamation() {
echo $(random_array_element ${EXCLAMATIONS[@]})
}
# Acá está la función que formatea las líneas y las imprime por pantalla
# todas las cuestiones relacionadas con modificación de apariencia de la salida
# de los mensajes debería ir por acá
# https://github.com/dylanaraps/pure-sh-bible#parsing-a-keyval-file
output_beautiful_messages() {
local last_user=''
local width=$(calculate_width)
while IFS="$SEPARATOR" read -r user message; do
if [[ $last_user != "$user" ]]; then
last_user="$user"
print_username "$user" $(choose_exclamation)
fi
print_message "$message" "$width"
done
}
# Toma el ancho de la terminal en columnas y le calcula un porcentaje a usar
# el porcentaje es 90%
# Devuelve la cantidad de columnas a usar
# por defecto 72 si no dispone de tput(1)
calculate_width() {
if ! type -p tput &>/dev/null; then
echo 72
else
local COLUMNS=$(tput cols)
local width=$((COLUMNS * 9 / 10))
echo "$width"
fi
}
# Imprime el nombre de usuario con todo el style
# Parámetros: nombre y opcionalmente un mensaje para poner al lado
# por defecto es 'dice:'
print_username() {
printf "${term_reverse}${term_bold} %s ${term_reset}" $1
printf "${term_dim}${term_italic} %s ${term_reset}\n" ${2:-'dice:'}
}
# Imprime un mensaje indentado y adaptado al ancho de columnas dado
# Parámetros: mensaje y ancho
print_message() {
printf '\t%s' "$1" | fmt $2
}
# Imprime las últimas n líneas del log de mensajes
# parámetro 1 es la cantidad de líneas a leer
# parámetro 2 es el path del archivo a leer
print_last_n_lines() {
tail -n "$1" "$GAB_LOG" | output_beautiful_messages
}
# Imprime cabecera
print_header() {
echo $TITLE
echo "Último mensaje: $LAST_MSG_DATE"
echo ""
}
# Agrega un mensaje al final del log de mensajes
# Primer parámetro: el mensaje
add_message() {
IFS=' ' # necesario para $*
msg=$(trim_string "$*")
echo "$USER $SEPARATOR $msg" >>"$GAB_LOG"
if [ $? -eq 0 ]; then
info "Mensaje agregado exitosamente al chatlog"
else
die "No se pudo agregar mensaje al chatlog" 1
fi
}
# Imprime los últimos mensajes
# Por defecto imprime 5
output_last_messages() {
# configuramos por defecto 5 líneas
lines=${1:-5}
print_header
print_last_n_lines "$lines"
}
# --- MAIN ---
if [ -z "$1" ]; then
output_last_messages
else
case "$1" in
-m | --msg)
if [ -z "$2" ]; then
die "Debe incluir un mensaje" 1
else
add_message ${@:2}
fi
;;
-l | --log)
if [ -z "$2" ]; then
output_last_messages
elif [[ $2 =~ ^[0-9]+$ ]]; then
output_last_messages $2
else
die "El valor debe ser un número entero" 1
fi
;;
-h | --help)
info "$HELP_TEXT"
;;
*)
echo "$HELP_TEXT"
die "Opción desconocida $1" 1
;;
esac
fi
|