network info (primary I/F) script; with workaround for Debian #798329 and iproute2...
[shellsnippets/shellsnippets.git] / mksh / g
1 #!/bin/mksh
2 #-
3 # Copyright © 2014, 2015
4 #       Thorsten Glaser <t.glaser@tarent.de>
5 #
6 # Provided that these terms and disclaimer and all copyright notices
7 # are retained or reproduced in an accompanying document, permission
8 # is granted to deal in this work without restriction, including un‐
9 # limited rights to use, publicly perform, distribute, sell, modify,
10 # merge, give away, or sublicence.
11 #
12 # This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
13 # the utmost extent permitted by applicable law, neither express nor
14 # implied; without malicious intent or gross negligence. In no event
15 # may a licensor, author or contributor be held liable for indirect,
16 # direct, other damage, loss, or other issues arising in any way out
17 # of dealing in the work, even if advised of the possibility of such
18 # damage or existence of a defect, except proven that it results out
19 # of said person’s immediate fault when using the work as intended.
20
21 function die {
22         print -r -- E: "$@"
23         exit 1
24 }
25
26 cr=$'\r'
27 nl=$'\n'
28 s=
29 st=0
30 while IFS= read -r line; do
31         case $st,${line%"$cr"} {
32         (0,*-----BEGIN\ PGP\ MESSAGE-----)
33                 p=${line%-----BEGIN\ PGP\ MESSAGE-----?("$cr")}
34                 c=${line#"$p"}$nl
35                 cs=
36                 st=1
37                 ;;
38         (0,*)
39                 s+=$line$nl
40                 ;;
41         (1,"$p"-----END\ PGP\ MESSAGE-----)
42                 die pgp message invalid
43                 ;;
44         (1,"$p"?(\ ))
45                 # switch from header to body; Enigmail bogusly adds a space
46                 st=2
47                 ;|
48         (2,"$p"-----END\ PGP\ MESSAGE-----)
49                 c+=${line#"$p"}
50                 c=$(print -r -- "$c" | gpg "$@") || die gpg failed
51                 x=
52                 [[ -z $cs ]] || if x=$(print -r -- "$c" | \
53                     iconv -f "$cs" -t utf-8); then
54                         c=$x
55                         x=
56                 else
57                         x="‣‣‣ WARNING: iconv from ${cs@Q} failed!$nl$nl"
58                 fi
59                 c=$nl$c
60                 c=${c//"$nl"/"$nl$p"}
61                 s+=$x${c#"$nl"}$nl
62                 st=0
63                 ;;
64         (1,"$p"Charset:*)
65                 cs=${line#"$p"Charset:}
66                 cs=${cs##+([     \r])}
67                 cs=${cs%%+([     \r])}
68                 ;&
69         ([12],"$p"*)
70                 c+=${line#"$p"}$nl
71                 ;;
72         ([12],*)
73                 die pgp message not indented consistently
74                 ;;
75         }
76 done
77 print -nr -- "$s"
78 exit 0