blob: 725cf21ffc7ee31e658a24c8322754a317889223 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
|
#!/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
|