-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpdvshell
More file actions
executable file
·5665 lines (5126 loc) · 194 KB
/
Copy pathpdvshell
File metadata and controls
executable file
·5665 lines (5126 loc) · 194 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# shellcheck shell=bash disable=SC1091,SC2039,SC2166,SC2162,SC2155,SC2005,SC2034,SC2154,SC2229
# pdvshell - Simples frente de caixa escrito em shell script e sqlite!
# Created: 2023/10/21
# Altered: 2024/11/20 - 02:21 -04
# Updated: sex 14 ago 2026 03:24:37 -04
#
# Copyright (c) 2023-2026, Vilmar Catafesta <vcatafesta@gmail.com>
# Copyright (c) 2023-2023, Jefferson Carneiro <slackjeff>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################
export TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN=pdvshell
#
declare APP="${0##*/}"
declare _VERSION_="0.08.12-20260812"
declare _SYSTEM_="PDVSHELL"
declare _SYSTEM_DESC="$(gettext "Simples frente de caixa escrito em shell script e sqlite")"
declare database='pdvshell.db'
declare INI_FILE="pdvshell.ini"
trap 'cleanup' INT TERM HUP
declare -A Aempresa=(
[razao]='EMPRESA MODELO LTDA'
[ende]='Rua Modelo, 693 - Bairro Centro'
[cida]='Cidade Modelo'
[uf]='UF'
[cnpj]='00.000.000/0001-00'
)
declare -a DEPENDENCIES=(
tput
gettext
sqlite3
bc
tr
sed
awk
figlet
)
declare -A PACKAGEDEP=(
['tput']='ncurses'
['gettext']='gettext'
['sqlite3']='sqlite'
['bc']='bc'
['tr']='coreutils'
['sed']='sed'
['awk']='gawk'
['figlet']='figlet'
)
readonly K_UP=5 # Ctrl-E
readonly K_DOWN=24 # Ctrl-X
readonly K_LEFT=19 # Ctrl-S
readonly K_RIGHT=4 # Ctrl-D
readonly K_HOME=1 # Ctrl-A
readonly K_END=6 # Ctrl-F
readonly K_PGUP=18 # Ctrl-R
readonly K_PGDN=3 # Ctrl-C
readonly K_ENTER=13 # Enter
readonly K_ESC=27 # Esc
# BEGIN FUNCTIONS
function cleanup() {
tput sgr0
tput clear
info_msg "${red}Interrompido! Saindo...${reset}"
info_msg "Desativando cores..."
sh_unsetvarcolors
exit 1
}
function sh_config() {
declare COL_NC='\e[0m' # No Color
declare COL_LIGHT_GREEN='\e[1;32m'
declare COL_LIGHT_RED='\e[1;31m'
declare -g TICK="${white}[${COL_LIGHT_GREEN}✓${COL_NC}${white}]"
declare -g CROSS="${white}[${COL_LIGHT_RED}✗${COL_NC}${white}]"
declare -gi lastrow=$(lastrow)
declare -gi lastcol=$(lastcol)
declare -gi Prow=0
declare -gi Pcol=0
declare -gi LC_DEFAULT=0
declare -gi nTop=8
declare -gi nLeft
declare -gi nBottom
declare -gi nRight
declare -g Mercearia='Mercearia'
declare -g Menu_Principal="$(gettext "Menu Principal")"
declare -g Nenhum_produto_encontrado_nos_parametros_informados="$(gettext "Nenhum produto encontrado nos parâmetros informados")"
declare -g Produtos="$(gettext "Produtos")"
declare -g Fornecedores="$(gettext "Fornecedores")"
declare -g Realizar_Venda_Saida="$(gettext "Realizar Venda/Saída")"
declare -g Entradas_de_Produtos="$(gettext "Entradas de Produtos")"
declare -g Pesquisa_Relatorio_Consulta="$(gettext "Pesquisa/Relatórios/Consulta")"
declare -g Manutencao="$(gettext "Manutenção")"
declare -g Configuracao="$(gettext "Configuração")"
declare -g Sair="$(gettext "Sair")"
declare -g Sair_do_Sistema="$(gettext "Sair do Sistema")"
declare -g Opcao_invalida="$(gettext "Opção inválida. Tente novamente.")"
declare -g Cadastrar="$(gettext 'Cadastrar')"
declare -g Inclusao="$(gettext 'Inclusão')"
declare -g Alterar="$(gettext 'Alterar')"
declare -g Alteracao="$(gettext 'Alteração')"
declare -g Remover_Excluir="$(gettext 'Remover/Excluir')"
declare -g Remocao="$(gettext 'Remoção')"
declare -g Exclusao="$(gettext 'Exclusão')"
declare -g Pesquisar="$(gettext 'Pesquisar')"
declare -g Consulta="$(gettext 'Consulta')"
declare -g Voltar="$(gettext 'Voltar')"
declare -g Registro_efetuado_com_sucesso="$(gettext "Registro efetuado com sucesso!")"
declare -g Registro_removido_com_sucesso="$(gettext "Registro removido com sucesso!")"
declare -g Erro_na_remocao_do_registro="$(gettext "Erro na remoção do registro!")"
declare -g Erro_no_cadastro_atualizacao_do_registro="$(gettext "Erro no cadastro/atualização do registro")"
declare -g Formato_de_data_invalida="$(gettext "Formato de data inicial inválida")"
declare -g Sobre="$(gettext "Sobre")"
declare -g Sobre_o="$(gettext "Sobre o")"
declare -g Consultas="$(gettext "Consultas")"
declare -g Movimento="$(gettext "Movimento")"
declare -g Relatorios="$(gettext "Relatórios")"
declare -g Relatorio_de="$(gettext "Relatório de")"
declare -g Produtos_abaixo_estoque_minimo="$(gettext 'Produtos abaixo estoque minímo')"
declare -g Produtos_fora_da_validade="$(gettext 'Produtos fora da validade')"
declare -g Vendas_Diarias="$(gettext 'Vendas Diárias')"
declare -g Produtos_Vendidos="$(gettext 'Produtos Vendidos')"
declare -g Atualizar_Estoque="$(gettext 'Atualizar Estoque (conciliação)')"
declare -g Popular_Databases="$(gettext 'Popular DataBases para testes')"
declare -g Zerar_Limpar_Produtos="$(gettext 'Zerar/Limpar DataBase Produtos')"
declare -g Zerar_Limpar_Fornecedor="$(gettext 'Zerar/Limpar DataBase Fornecedor')"
declare -g Zerar_Limpar_Vendas="$(gettext 'Zerar/Limpar DataBase Vendas')"
declare -g Zerar_Limpar_Compras="$(gettext 'Zerar/Limpar DataBase Compras')"
declare -g Dados_Empresa="$(gettext 'Dados Empresa')"
declare -g Aparencia="$(gettext 'Aparência')"
declare -g Pano_de_fundo="$(gettext 'Pano de fundo')"
declare -gi pselecionadoV=1
declare -gi pselecionadoH=1
}
function sh_environment() {
local result
local -a aempresa=('razao' 'ende' 'cida' 'uf' 'cnpj')
local -a acores=('cabecalho' 'logo' 'statussup' 'statusinf' 'box' 'boxtitle' 'dispbox' 'msgok' 'msgerror' 'conf' 'panofundo' 'corpanofundo')
local i
declare -gA Acores=(
[cabecalho]="$roxo"
[logo]="$red"
[statussup]="$ciano"
[statusinf]="$azul"
[box]="$azul"
[boxtitle]="${reverse}$azul"
[dispbox]="$cinza"
[msgok]="$green"
[msgerror]="$red"
[conf]="$red"
[panofundo]="█▓░▒pdvShell█▒▓░"
[corpanofundo]="$cinza"
)
if [[ -e "$INI_FILE" ]]; then
for i in ${aempresa[@]}; do
result=
if result="$(TIni.Get "$INI_FILE" "empresa" "$i")" && [[ -n "$result" ]]; then Aempresa["$i"]="$result"; fi
done
for i in ${acores[@]}; do
result=
if result="$(TIni.Get "$INI_FILE" "cores" "$i")" && [[ -n "$result" ]]; then Acores["$i"]="$result"; fi
done
fi
unset result aempresa acores i
}
# Gera a sequência ANSI de cor de texto (equivalente a "tput setaf N"),
# sem disparar processo externo. Testado contra o tput real para as 256
# cores possíveis (0-255), sem nenhuma divergência.
function ansi_setaf() {
local n="$1"
if ((n < 8)); then
printf "\e[3%dm" "$n"
elif ((n < 16)); then
printf "\e[9%dm" "$((n - 8))"
else
printf "\e[38;5;%dm" "$n"
fi
}
# Gera a sequência ANSI de cor de fundo (equivalente a "tput setab N"),
# sem disparar processo externo. Mesma validação de ansi_setaf().
function ansi_setab() {
local n="$1"
if ((n < 8)); then
printf "\e[4%dm" "$n"
elif ((n < 16)); then
printf "\e[10%dm" "$((n - 8))"
else
printf "\e[48;5;%dm" "$n"
fi
}
# Extrai o número da cor (0-255) de uma sequência ANSI já montada (mesmo
# que composta com outros códigos como bold/reverse). Usada para descobrir
# em qual cor a tela de seleção deve começar, a partir do valor atual em
# Acores[$ctype]. Devolve vazio se não conseguir identificar.
function ansi_extrair_cor() {
local seq="$1"
local n=""
if [[ "$seq" =~ \[[34]8\;5\;([0-9]+)m ]]; then
n="${BASH_REMATCH[1]}"
elif [[ "$seq" =~ \[3([0-7])m ]]; then
n="${BASH_REMATCH[1]}"
elif [[ "$seq" =~ \[4([0-7])m ]]; then
n="${BASH_REMATCH[1]}"
elif [[ "$seq" =~ \[9([0-7])m ]]; then
n=$((BASH_REMATCH[1] + 8))
elif [[ "$seq" =~ \[10([0-7])m ]]; then
n=$((BASH_REMATCH[1] + 8))
fi
echo "$n"
}
function sh_setvarcolors() {
# does the terminal support true-color?
if [[ -n "$(command -v "tput")" ]]; then
#tput setaf 127 | cat -v #capturar saida
reset=$'\e(B\e[m'
rst=$'\e(B\e[m'
bold=$'\e[1m'
underline=$'\e[4m'
nounderline=$'\e[24m'
reverse=$'\e[7m'
black=$bold$(ansi_setaf 0)
red=$bold$(ansi_setaf 196)
green=$bold$(ansi_setaf 2)
yellow=$bold$(ansi_setaf 3)
# blue=$(ansi_setaf 4)
blue=$(ansi_setaf 27)
magenta=$(ansi_setaf 5)
cyan=$(ansi_setaf 6)
white=$(ansi_setaf 7)
gray=$(ansi_setaf 8)
light_red=$(ansi_setaf 9)
light_green=$(ansi_setaf 10)
light_yellow=$(ansi_setaf 11)
light_blue=$(ansi_setaf 12)
light_magenta=$(ansi_setaf 13)
light_cyan=$(ansi_setaf 14)
light_white=$(ansi_setaf 15)
orange=$(ansi_setaf 202)
purple=$(ansi_setaf 125)
violet=$(ansi_setaf 61)
# Definir cores de fundo
preto=$(ansi_setab 0)
vermelho=$(ansi_setab 196)
verde=$(ansi_setab 2)
amarelo=$(ansi_setab 3)
azul=$(ansi_setab 20)
roxo=$(ansi_setab 5)
ciano=$(ansi_setab 6)
branca="${black}$(ansi_setab 7)"
cinza=$(ansi_setab 8)
laranja=$(ansi_setab 202)
roxa=$(ansi_setab 125)
violeta=$(ansi_setab 61)
else
sh_unsetvarcolors
fi
}
function sh_unsetvarcolors() {
unset reset rst bold underline nounderline reverse
unset black red green yellow blue magenta cyan white gray orange purple violet
unset light_red light_green light_yellow light_blue light_magenta light_cyan light_white
unset preto vermelho verde amarelo azul roxo ciano branca cinza laranja roxa violeta
}
function detect_distro() {
local id=""
if [[ -r /etc/os-release ]]; then
# Lê ID=void|arch|debian|... exatamente como a distro declara
id=$(grep -E '^ID=' /etc/os-release | cut -d= -f2 | tr -d '"')
elif [[ -r /usr/lib/os-release ]]; then
id=$(grep -E '^ID=' /usr/lib/os-release | cut -d= -f2 | tr -d '"')
else
echo "unknown"
return
fi
echo "$id"
}
function cmd_sudo() {
if [[ $EUID -eq 0 ]]; then
"$@"
else
sudo "$@"
fi
}
function sh_setup_Packages() {
local packagesToInstall="${PACKAGEDEP[@]}"
local DISTRO=$(detect_distro)
case "$DISTRO" in
void)
msg_info "Instalando necessários pacotes para VOID"
cmd_sudo xbps-install -Sy "${PACKAGEDEP[@]}" 1>/dev/null
return "$?"
;;
chili | chililinux | arch | manjaro | biglinux)
msg_info "Instalando necessários pacotes para ${DISTRO^^}VOID"
sudo pacman -Sy --needed --quiet --noconfirm "${PACKAGEDEP[@]}" 1>/dev/null
return "$?"
;;
*)
return 1
;;
esac
}
function sh_checkDependencies() {
local d
local errorFound=false
declare -a missing
for d in "${DEPENDENCIES[@]}"; do
if ! command -v "$d" &>/dev/null; then
info_msg "${red}Erro${rst}: Não foi possível encontrar o comando ${cyan}'$d'${rst} -> instalar o pacote ${cyan}${PACKAGEDEP[$d]}${rst}"
missing+=("$d")
errorFound=true
fi
done
if $errorFound; then
echo "${yellow}-----------------IMPOSSÍVEL CONTINUAR---------------${rst}"
echo "Este script precisa dos comandos listados acima"
echo "Instale-os e/ou verifique se eles estão em seu ${red}\$PATH${rst}"
echo "${yellow}-----------------IMPOSSÍVEL CONTINUAR---------------${rst}"
if conf "Deseja instalar os pacotes necessários ?"; then
sh_setup_Packages
sh_checkDependencies #overload
else
die "Encerrando..."
fi
fi
}
# Função para verificar se um valor em uma seção corresponde a um valor de referência em um arquivo INI
# TIni.ExistValue "config.ini" "flatpak" "active" '0'; echo $?
function TIni.ExistValue {
local config_file="$1"
local section="$2"
local key="$3"
local comp_value="$4"
if [[ -f "$config_file" ]]; then
local section_found=false
local key_found=false
local value=""
local line
while IFS= read -r line; do
if [[ "$line" == "[$section]" ]]; then
section_found=true
elif [[ "$line" == "["* ]]; then
section_found=false
fi
if [[ "$section_found" == true && "$line" == "$key="* ]]; then
value=$(echo "$line" | cut -d'=' -f2)
key_found=true
fi
if [[ "$section_found" == true && "$key_found" == true ]]; then
if [[ "$value" == "$comp_value" ]]; then
return 0 # Valor encontrado e corresponde ao valor de referência
else
return 1 # Valor encontrado, mas não corresponde ao valor de referência
fi
fi
done <"$config_file"
fi
return 2 # Seção ou chave não encontrada no arquivo INI
}
export -f TIni.ExistValue
# Função para ler um valor do arquivo INI
# TIni.ReadValue "config.ini" "flatpak" "active"
function TIni.ReadValue() {
local config_file="$1"
local section="$2"
local key="$3"
local found_section=false
local line
# Variável para armazenar o valor encontrado
local value=""
# Use grep para encontrar a chave na seção especificada no arquivo INI
while IFS= read -r line; do
if [[ "$line" =~ ^\[$section\] ]]; then
found_section=true
elif [[ "$found_section" == true && "$line" =~ ^$key= ]]; then
# Encontramos a chave dentro da seção
value=$(echo "$line" | cut -d'=' -f2)
break # Saia do loop, pois encontramos o valor
elif [[ "$line" =~ ^\[.*\] ]]; then
# Se encontrarmos outra seção, saia do loop para evitar procurar em outras seções
found_section=false
fi
done <"$config_file"
# Verifique se encontramos o valor
if [[ -n "$value" ]]; then
echo "$value"
return 0
fi
return 1
}
export -f TIni.ReadValue
function TIni.Get() {
local config_file="$1"
local section="$2"
local key="$3"
local line in_section=false value=""
[[ -f "$config_file" ]] || return 1
while IFS= read -r line; do
if [[ "$line" == "[$section]" ]]; then
in_section=true
continue
elif [[ "$line" == \[*\] ]]; then
in_section=false
continue
fi
if $in_section && [[ "$line" =~ ^[[:space:]]*${key}[[:space:]]*= ]]; then
value="${line#*=}"
[[ "$value" =~ ^[[:space:]]*(.*)$ ]] && value="${BASH_REMATCH[1]}"
break
fi
done <"$config_file"
if [[ -n "$value" ]]; then
echo "$value"
return 0
fi
return 1
}
export -f TIni.Get
# Exemplo de uso: TIni.Set arquivo.ini snap vilmar 5.7
function TIni.Set() {
local config_file="$1"
local section="$2"
local key="$3"
local value="$4"
local found_section=0
local line
if [ ! -f "$config_file" ]; then
# Se não existir, crie o arquivo com a seção, chave e valor fornecidos
{
echo "[$section]"
echo "$key=$value"
} >>"$config_file"
return
fi
while IFS= read -r line; do
if [[ "$line" =~ ^\[$section\] ]]; then
found_section=1
elif [[ "$line" =~ ^\[.*\] ]]; then
# Entrou em OUTRA seção: reseta found_section, senão uma nova
# chave acabava sendo gravada na última seção do arquivo em
# vez da seção correta (bug: found_section nunca voltava a 0).
found_section=0
elif [[ "$found_section" -eq 1 && "${line}" =~ ^${key}[[:space:]]*=[[:space:]]* ]]; then
# Se a seção e a chave existem, atualize o valor.
# Escapa caracteres com significado especial na substituição do
# sed: \ (escape), & (texto casado) e | (delimitador usado
# aqui) - sem isso, um valor como "Bar & Mercearia" corrompia
# a gravação (o & era substituído pelo texto original casado).
local value_escaped="${value//\\/\\\\}"
value_escaped="${value_escaped//&/\\&}"
value_escaped="${value_escaped//|/\\|}"
sed -i "s|^${key}[[:space:]]*=[[:space:]]*.*|${key}=${value_escaped}|" "$config_file"
return
fi
done <"$config_file"
# Se a seção não existir, crie-a e adicione a chave e o valor
if [[ "$found_section" -eq 0 ]]; then
{
echo ""
echo "[$section]"
} >>"$config_file"
fi
echo "$key=$value" >>"$config_file"
}
export -f TIni.Set
function TIni.Sanitize() {
local ini_file="$1"
local tempfile1
local tempfile2
# Criar arquivos temporários
tempfile1=$(mktemp)
tempfile2=$(mktemp)
# Remover linhas em branco do arquivo original
sed '/^$/d' "$ini_file" >"$tempfile1"
# Consolidar seções usando awk e salvar no segundo arquivo temporário
awk '
BEGIN {
section = ""
}
{
if ($0 ~ /^\[.*\]$/) {
section = $0
} else if (section != "") {
sections[section] = sections[section] "\n" $0
}
}
END {
for (section in sections) {
print section sections[section] "\n"
}
}
' "$tempfile1" >"$tempfile2"
sed '/^\s*$/d' "$tempfile2" >"$ini_file"
# colocar uma linha em branco entre as sessoes e remover a primeira linha em branco
sed -i -e '/^\[/s/\[/\n&/' -e '1{/^[[:space:]]*$/d}' "$ini_file"
sed -i -e '1{/^[[:space:]]*$/d}' "$ini_file"
# marcar como executável
chmod +x "$ini_file"
# Remover arquivos temporários
rm "$tempfile1" "$tempfile2"
}
export -f TIni.Sanitize
function TIni.Clean() {
local ini_file="$1"
sed -i -e '/./,$!d' -e 's/[ \t]*=[ \t]*/=/' "$ini_file"
# awk -F'=' '{
# gsub(/^[ \t]+|[ \t]+$/, "", $1);
# gsub(/^[ \t]+|[ \t]+$/, "", $2);
# print $1 "=" $2
# }' "$ini_file" | tee "$ini_file"
}
export -f TIni.Clean
# Se a chave e o valor forem exatamente iguais, a função retorna 0.
# Se a chave for encontrada, mas o valor não for igual, a função retorna 2.
# Se a chave não for encontrada, a função retorna 1.
# Se a chave for encontrada com um ponto e vírgula no início, a função também retorna 2.
function TIni.Exist() {
local config_file="$1"
local section="$2"
local key="$3"
local value="$4"
local result=1 # Inicializa como 1, indicando que a chave não foi encontrada
[[ ! -e "$config_file" ]] && return 2
result=$(awk -F "=" -v section="$section" -v key="$key" -v value="$value" '
BEGIN {
encontrado = 1 # Inicializa como 1, indicando que a chave não foi encontrada
}
{
gsub(/^[ \t]+|[ \t]+$/, "", $1); # Remova espaços em branco em torno do nome da chave
if ($0 ~ "^\\[" section "\\]") { # Verifique se estamos na seção correta
in_section = 1
} else if (in_section) {
if ($1 == key) { # Se estivermos na seção correta, procure a chave
if ($0 ~ /^[[:space:]]*;/) {
encontrado = 2 # Chave encontrada com ponto e vírgula no início
exit
}
gsub(/^[ \t]+|[ \t]+$/, "", $2); # Remova espaços em branco em torno do valor
if ($0 !~ /^[[:space:]]*;/) { # Verifique se não é um comentário
if (value == "") {
encontrado = 0 # Chave encontrada sem valor especificado
exit
} else if ($2 == value) {
encontrado = 0 # Chave encontrada com o valor correto
exit
} else {
encontrado = 2 # Valor fornecido não é igual ao valor da chave
exit
}
}
}
} else if ($0 ~ "^\\[.*\\]") { # Se encontrarmos outra seção, saia da seção atual
in_section = 0
}
}
END {
print encontrado
}
' "$config_file")
return "$result"
}
export -f TIni.Exist
# Escapa aspas simples (') para uso seguro dentro de literais SQL ('...').
# Regra padrão SQL: cada aspa simples vira duas aspas simples.
# Uso: sql_escape "$valor_do_usuario"
function sql_escape() {
printf '%s' "${1//\'/\'\'}"
}
export -f sql_escape
function sh_splitarray() {
local str=("$1")
local pos="${2:-1}"
local sep="${3:-'|'}"
local array
# Corrigir argumentos se a ordem for invertida ou ausente
[[ "$pos" == "$sep" ]] && {
sep="${2:-'|'}"
pos="${3:-1}"
}
IFS="$sep" read -r -a array <<<"$str"
echo "${array[pos - 1]}"
}
function len_split_str() {
local anew
IFS='|' read -r -a anew <<<"$1"
echo "${#anew[@]}"
}
function padr() {
local texto=$1
local COLS=$2
local char=$3
if test $# -eq 1; then
COLS=$(tput cols)
char='='
fi
printf "%*s\n" "$COLS" "$texto" | sed "s/ /$char/g"
}
function padl() {
local texto=$1
local COLS=$2
local char=$3
if test $# -eq 1; then
COLS=$(tput cols)
char='='
fi
printf "%-*s\n" $COLS "$texto" | sed "s/ /$char/g"
}
function padc() {
local texto=$1
local COLS=$2
local char=$3
if test $# -eq 1; then
COLS=$(tput cols)
char='='
fi
printf "%*s\n" $(((${#texto} + $COLS) / 2)) "$texto" | sed "s/ /$char/g"
}
# Calcula larguras de campo ajustadas à largura disponível do terminal:
# campos flexíveis encolhem (nunca abaixo do mínimo) para caber; campos
# fixos nunca mudam. Se houver espaço de sobra, mantém as larguras ideais
# (não estica além do necessário). Resultado em CALC_LARGURAS_RESULT, na
# mesma sintaxe pipe-separated do Max_field_width.
# Uso: calcular_larguras "5|40|2|5" "0|1|0|0" "$largura_disponivel" [minimo]
function calcular_larguras() {
local ideais="$1"
local flex="$2"
local disponivel="$3"
local minimo="${4:-6}"
local -a a_ideais a_flex
IFS='|' read -r -a a_ideais <<<"$ideais"
IFS='|' read -r -a a_flex <<<"$flex"
local n=${#a_ideais[@]}
local i
local total_ideal=0
for i in "${!a_ideais[@]}"; do
total_ideal=$((total_ideal + a_ideais[i]))
done
# soma dos separadores '|' entre campos (n-1) + 2 bordas da caixa
total_ideal=$((total_ideal + n - 1 + 2))
if ((total_ideal == disponivel)); then
CALC_LARGURAS_RESULT="$ideais"
return 0
fi
local -a a_result=("${a_ideais[@]}")
if ((total_ideal < disponivel)); then
# sobra espaço: distribui proporcionalmente entre as colunas
# marcadas como flexíveis, pra ocupar toda a área disponível
local sobra=$((disponivel - total_ideal))
local total_flex=0
for i in "${!a_ideais[@]}"; do
[[ "${a_flex[i]}" == "1" ]] && total_flex=$((total_flex + a_ideais[i]))
done
if ((total_flex > 0)); then
for i in "${!a_ideais[@]}"; do
if [[ "${a_flex[i]}" == "1" ]]; then
local acrescimo=$((sobra * a_ideais[i] / total_flex))
a_result[i]=$((a_ideais[i] + acrescimo))
fi
done
# ajuste fino: sobra de arredondamento vai pro 1º campo flexível
local total_atual=0
for i in "${!a_result[@]}"; do
total_atual=$((total_atual + a_result[i]))
done
total_atual=$((total_atual + n - 1 + 2))
local resto=$((disponivel - total_atual))
if ((resto > 0)); then
for i in "${!a_ideais[@]}"; do
if [[ "${a_flex[i]}" == "1" ]]; then
a_result[i]=$((a_result[i] + resto))
break
fi
done
fi
fi
local resultado=""
for i in "${!a_result[@]}"; do
[[ -n "$resultado" ]] && resultado+="|"
resultado+="${a_result[i]}"
done
CALC_LARGURAS_RESULT="$resultado"
return 0
fi
# total_ideal > disponivel: não cabe, precisa encolher
local excesso=$((total_ideal - disponivel))
local total_flex=0
for i in "${!a_ideais[@]}"; do
[[ "${a_flex[i]}" == "1" ]] && total_flex=$((total_flex + a_ideais[i]))
done
if ((total_flex > 0)); then
for i in "${!a_ideais[@]}"; do
if [[ "${a_flex[i]}" == "1" ]]; then
local reducao=$((excesso * a_ideais[i] / total_flex))
local nova=$((a_ideais[i] - reducao))
((nova < minimo)) && nova=$minimo
a_result[i]=$nova
fi
done
fi
# ajuste fino: tira 1 de cada vez do maior campo flexível até bater exato
local total_atual=0
for i in "${!a_result[@]}"; do
total_atual=$((total_atual + a_result[i]))
done
total_atual=$((total_atual + n - 1 + 2))
while ((total_atual > disponivel)); do
local idx_maior=-1
local maior_valor=0
for i in "${!a_ideais[@]}"; do
if [[ "${a_flex[i]}" == "1" && ${a_result[i]} -gt $minimo && ${a_result[i]} -gt $maior_valor ]]; then
maior_valor=${a_result[i]}
idx_maior=$i
fi
done
((idx_maior == -1)) && break
a_result[idx_maior]=$((a_result[idx_maior] - 1))
total_atual=$((total_atual - 1))
done
local resultado=""
for i in "${!a_result[@]}"; do
[[ -n "$resultado" ]] && resultado+="|"
resultado+="${a_result[i]}"
done
CALC_LARGURAS_RESULT="$resultado"
}
# Navegador de tabela estilo Browse()/TBrowse do Clipper/Harbour: mostra
# dados tabulares com scroll vertical (só desenha as linhas visíveis,
# nunca estoura o terminal por maior que seja o conjunto de dados) e
# navegação por setas/PgUp/PgDn/Home/End/Enter/ESC.
#
# Uso: browse_tabela linha coluna altura largura "Título" "Cab|eça|lho" "Larg|uras" nome_array [cor] [cores_colunas]
# título: aparece centralizado na borda superior da caixa, igual o
# show_menu()/box() já fazem. Pode ser vazio ("") se não precisar.
#
# nome_array: nome de um array bash já populado, cada elemento é uma
# linha de dados pipe-delimited (mesmo número de campos do cabeçalho).
# Uma linha aceita 3 formatos:
# N campos (padrão) : sem cor especial, usa cor da coluna/padrão
# N+1 campos : último campo = cor da LINHA inteira
# (ex: "5|Produto X|10|$vermelho")
# N*2 campos : segunda metade = cor por CÉLULA, uma
# por coluna desta linha (ex: campo de
# estoque com cor diferente por sinal:
# "5|Produto X|-3|10|||$vermelho||")
#
# cores_colunas (opcional): define uma cor fixa por COLUNA (aplicada
# em todas as linhas que não sobrescrevem via cor de linha/célula),
# mesma sintaxe pipe-delimited das larguras (ex: "|||$cyan||$red"
# pinta só a 5ª e a última coluna). Campo vazio = cor padrão da caixa.
#
# Prioridade quando mais de uma coexiste: cor de LINHA sempre vence
# (destaca a linha inteira sem exceção) > cor de CÉLULA (varia célula
# a célula dentro da mesma linha) > cor de COLUNA (fixa, igual em
# todas as linhas) > cor padrão da caixa. A linha atualmente
# selecionada (em vídeo reverso) sempre usa cor uniforme, ignorando
# cores de célula/coluna, para não cortar o reverso no meio da linha.
#
# Retorno: 0 = ENTER (BROWSE_SELECIONADO=índice 0-based,
# BROWSE_LINHA_SELECIONADA=linha de dado escolhida)
# 1 = ESC (cancelado) ou falha de leitura de tecla
# 2 = array vazio (nada a mostrar)
function browse_tabela() {
local linha="$1" col="$2" altura="$3" largura="$4"
local titulo_caixa="$5"
local cabecalho="$6"
local larguras="$7"
local -n browse_dados="$8"
local color="${9:-${Acores[box]}}"
local cores_colunas="${10:-}"
local total=${#browse_dados[@]}
local visiveis=$((altura - 3))
local topo=0 atual=0
local -a a_larguras a_cabecalho a_cores_col
IFS='|' read -r -a a_larguras <<<"$larguras"
IFS='|' read -r -a a_cabecalho <<<"$cabecalho"
[[ -n "$cores_colunas" ]] && IFS='|' read -r -a a_cores_col <<<"$cores_colunas"
local i j idx campo linha_fmt valor cor_campo
BROWSE_SELECIONADO=""
BROWSE_LINHA_SELECIONADA=""
if ((total == 0)); then
return 2
fi
((visiveis < 1)) && visiveis=1
while true; do
box "$linha" "$col" "$altura" "$largura" "$titulo_caixa" "$color"
setpos "$((linha + 1))" "$((col + 1))"
linha_fmt=""
for i in "${!a_cabecalho[@]}"; do
utf8_campo "${a_cabecalho[i]}" "${a_larguras[i]}"
linha_fmt+="$UTF8_CAMPO_RESULT"
((i < ${#a_cabecalho[@]} - 1)) && linha_fmt+="|"
done
printf "%s%s%s" "${Acores[dispbox]}" "$linha_fmt" "$reset"
for ((i = 0; i < visiveis; i++)); do
idx=$((topo + i))
setpos "$((linha + 2 + i))" "$((col + 1))"
if ((idx < total)); then
local -a campos_linha
# o "|" extra no final evita que o read -a descarte um
# campo vazio no final da linha (bug conhecido do bash:
# "a|b|" lê só 2 campos em vez de 3) - sem isso, uma
# linha N×2 (cor por célula) com a última cor vazia
# perde um campo e quebra a detecção do formato.
IFS='|' read -r -a campos_linha <<<"${browse_dados[idx]}|"
local cor_linha=""
local -a cores_celula=()
if ((${#campos_linha[@]} == 2 * ${#a_larguras[@]})); then
# metade dos campos são cor por CÉLULA (uma por coluna
# desta linha específica, ex: estoque negativo em
# vermelho, positivo em ciano - varia célula a célula)
cores_celula=("${campos_linha[@]:${#a_larguras[@]}}")
campos_linha=("${campos_linha[@]:0:${#a_larguras[@]}}")
elif ((${#campos_linha[@]} > ${#a_larguras[@]})); then
cor_linha="${campos_linha[-1]}"
unset 'campos_linha[-1]'
fi
if ((idx == atual)); then
# Linha selecionada: sempre uniforme (reverso + cor de
# linha, sem cor por campo) - um reset no meio do
# caminho cancelaria o vídeo reverso pro resto da linha.
linha_fmt=""
for j in "${!a_larguras[@]}"; do
utf8_campo "${campos_linha[j]}" "${a_larguras[j]}"
linha_fmt+="$UTF8_CAMPO_RESULT"
((j < ${#a_larguras[@]} - 1)) && linha_fmt+="|"
done
printf "%s%s%s%s" "$reverse" "$cor_linha" "$linha_fmt" "$reset"
else
linha_fmt=""
for j in "${!a_larguras[@]}"; do
utf8_campo "${campos_linha[j]}" "${a_larguras[j]}"
campo="$UTF8_CAMPO_RESULT"
if [[ -n "$cor_linha" ]]; then
linha_fmt+="$campo"
else
cor_campo="${cores_celula[j]:-${a_cores_col[j]:-}}"
if [[ -n "$cor_campo" ]]; then
linha_fmt+="${cor_campo}${campo}${reset}"
else
linha_fmt+="$campo"
fi
fi
((j < ${#a_larguras[@]} - 1)) && linha_fmt+="|"
done
printf "%s%s%s" "$cor_linha" "$linha_fmt" "$reset"
fi
fi
done
read_key || return 1
case "$LAST_KEY" in
"$K_UP")
if ((atual > 0)); then
((atual--))
((atual < topo)) && ((topo--))
fi
;;
"$K_DOWN")
if ((atual < total - 1)); then
((atual++))
((atual >= topo + visiveis)) && ((topo++))
fi
;;
"$K_PGUP")
atual=$((atual - visiveis))
((atual < 0)) && atual=0
topo=$atual
;;
"$K_PGDN")
atual=$((atual + visiveis))
((atual >= total)) && atual=$((total - 1))
topo=$((atual - visiveis + 1))
((topo < 0)) && topo=0
;;
"$K_HOME")
atual=0
topo=0
;;
"$K_END")
atual=$((total - 1))
topo=$((total - visiveis))
((topo < 0)) && topo=0
;;
"$K_ENTER")
BROWSE_SELECIONADO=$atual
BROWSE_LINHA_SELECIONADA="${browse_dados[atual]}"
return 0
;;
"$K_ESC")
return 1
;;
esac
done
}
# dispbox "0|0|6" "ID|DESCRICAO DO PRODUTO|ESTOQUE|PREÇO" "5|40|5|11" "$cinza" 'left'
function dispbox() {
local -A Aarray
Aarray[coord]="$1"
Aarray[cabec]="$2"
Aarray[len]="$3"
local color="$4"