-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathapt-cyg
2637 lines (2296 loc) · 69.3 KB
/
apt-cyg
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
# apt-cyg: install tool for cygwin similar to debian apt-get
# The MIT License (MIT)
#
# Copyright (c) 2013 Trans-code Design
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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 OR COPYRIGHT HOLDERS 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.
#
# EMBED_BEGIN: hhs_embed
(( 5 <= DEBUG )) && set -x
SCRIPT_PATH="$0"
SCRIPT_FILE="${SCRIPT_PATH##*/}"
SCRIPT_NAME="${SCRIPT_FILE%.*}"
SCRIPT_DIR="${SCRIPT_PATH%/*}"
SCRIPT_REALPATH="$(readlink -f "$SCRIPT_PATH")"
SCRIPT_REALFILE="${SCRIPT_REALPATH##*/}"
SCRIPT_REALNAME="${SCRIPT_REALFILE%.*}"
SCRIPT_REALDIR="${SCRIPT_REALPATH%/*}"
# EMBED_BEGIN: hhs_sgr.bash
function init_SGR ()
{
if [ -n "$COLORIZE" ]; then
SGR_reset="\e[0m"
SGR_bold="\e[1m"
SGR_fg_red="\e[31m"
SGR_fg_green="\e[32m"
SGR_fg_yellow="\e[33m"
SGR_fg_blue="\e[34m"
SGR_fg_magenta="\e[35m"
else
unset SGR_reset SGR_bold SGR_red SGR_green SGR_yellow SGR_blue SGR_magenta
fi
FATAL_COLOR="${SGR_fg_magenta}${SGR_bold}"
ERROR_COLOR="${SGR_fg_red}${SGR_bold}"
WARNING_COLOR="${SGR_fg_yellow}${SGR_bold}"
INFO_COLOR="${SGR_fg_green}${SGR_bold}"
DEBUG_COLOR="${SGR_fg_blue}${SGR_bold}"
}
# EMBED_END: hhs_sgr.bash
# EMBED_BEGIN: hhs_debug.bash
THRESHOLD_OF_FATAL=0
THRESHOLD_OF_ERROR=1
THRESHOLD_OF_WARNING=2
THRESHOLD_OF_INFO=3
THRESHOLD_OF_DEBUG=4
function abort () #= [EXITCODE=1 [CALLSTACKSKIP=0]]
{
dump_callstack $(( 2 + ${2:-0} ))
exit "${1:-1}"
}
function assert_command_exists () #= [COMMAND ...]
{
local command
for command in $@; do
hash $command 2>/dev/null || { error "Required command [$command] not found."; exit 1; }
done
}
function dump_callstack () #= [N=1]
#? N is a depth to skip the callstack.
#? $CALLSTACK_SKIP is depth to skip the callstack too.
#? N and CALLSTACK_SKIP is summed before skipping.
#? The default value is N = 1 and CALLSTACK_SKIP = 0.
{
local i
echo "Callstack:"
for i in `seq "$(( ${#FUNCNAME[@]} - 1 ))" -1 $(( ${1:-1} + ${CALLSTACK_SKIP:-0} ))`; do
echo -e "\t${BASH_SOURCE[i]}: ${FUNCNAME[i]}: ${BASH_LINENO[i-1]}"
done
} #/dump_callstack
function source_at () #= [N=1]
{
local i=${1:-1}
echo -e "${DEBUG_COLOR}at :${SGR_reset} ${BASH_SOURCE[i-1]}: ${FUNCNAME[i]}: ${BASH_LINENO[i-1]}"
}
function fatal () #= [MESSAGES ...]
{
(( THRESHOLD_OF_FATAL <= ${VERBOSE:-0} )) || return 1
echo -e "${FATAL_COLOR}Fatal:${SGR_reset} $@"
(( THRESHOLD_OF_FATAL <= SOURCE_AT )) && source_at 2
} >&2 #/fatal
function error () #= [MESSAGES ...]
{
(( THRESHOLD_OF_ERROR <= ${VERBOSE:-0} )) || return 1
echo -e "${ERROR_COLOR}Error:${SGR_reset} $@"
(( THRESHOLD_OF_ERROR <= SOURCE_AT )) && source_at 2
} >&2 #/error
function warning () #= [MESSAGES ...]
{
(( THRESHOLD_OF_WARNING <= ${VERBOSE:-0} )) || return 1
echo -e "${WARNING_COLOR}Warning:${SGR_reset} $@"
(( THRESHOLD_OF_WARNING <= SOURCE_AT )) && source_at 2
} >&2 #/warning
function info () #= [MESSAGES ...]
{
(( THRESHOLD_OF_INFO <= ${VERBOSE:-0} )) || return 1
echo -e "${INFO_COLOR}Info:${SGR_reset} $@"
(( THRESHOLD_OF_INFO <= SOURCE_AT )) && source_at 2
} >&2 #/info
function debug () #= [MESSAGES ...]
{
(( THRESHOLD_OF_DEBUG <= ${VERBOSE:-0} )) || return 1
echo -e "${DEBUG_COLOR}Debug:${SGR_reset} $@"
(( THRESHOLD_OF_DEBUG <= SOURCE_AT )) && source_at 2
} >&2 #/debug
# EMBED_END: hhs_debug.bash
: ${VERBOSE:=$THRESHOLD_OF_WARNING}
: ${SOURCE_AT:=$THRESHOLD_OF_WARNING}
: ${COLORIZE:=1}
init_SGR
# EMBED_END: hhs_embed
TRUSTEDKEYS=( CYGWIN );
# ./pubring.asc
# ------------
# pub 4096R/E2E56300 2020-02-27 [expires: 2022-02-26]
# uid Cygwin <[email protected]>
TRUSTEDKEY_CYGWIN_SUM="6291bf8f958e1ea05501b91d776ea10b2cd781c5caeb3d72da63333e5c45698fa4766d524a2d9a128b09b8446ee7e25cbb7942ee49d7409583e712d5c68ee81e"
TRUSTEDKEY_CYGWIN_FPR="56405CF6FCC81574682A5D561A698DE9E2E56300"
TRUSTEDKEY_CYGWIN_URL_LATEST="https://cygwin.com/key/pubring.asc"
# this script requires some packages
WGET="$( type -p wget 2>/dev/null )"
TAR="$( type -p tar 2>/dev/null )"
GAWK="$( type -p awk 2>/dev/null )"
GPG="$( type -p gpg 2>/dev/null || type -p gpg2 2>/dev/null )"
if [ -z "$WGET" -o -z "$TAR" -o -z "$GAWK" ]; then
echo You must install wget, tar and gawk to use apt-cyg.
exit 1
fi
function usage()
{
cat<<-EOD
Usage: apt-cyg [<options>] [<subcommand> [<parameters> ...]]
Installs and removes Cygwin packages.
Subcommands:
install <package names> : to install packages
remove <package names> : to remove packages
update : to update setup.ini
show : to show installed packages
find <patterns> ... : to find packages matching patterns
describe <patterns> ... : to describe packages matching patterns
packageof <command or file names> ... :
to locate parent packages
pathof {cache|mirror|mirrordir|cache/mirrordir|setup.ini} :
to show path
key-add <files> ... : to add keys contained in <files>
key-del <keyids> ... : to remove keys <keyids>
key-list : to list keys
key-finger : to list fingerprints
upgrade-self : to upgrade apt-cyg
depends <package names> ... :
to show forward dependency information
for packages with depth.
rdepends <package names> ... :
to show reverse dependency information
for packages with depth.
completion-install : to install completion.
completion-uninstall : to uninstall completion.
mirrors-list : to show list of mirros.
mirrors-list-long : to show list of mirros with full details.
mirrors-list-online : to show list of mirros from online.
benchmark-mirrors <urls> ... :
to benchmark mirrors.
benchmark-parallel-mirrors <urls> ... :
to benchmark mirrors in parallel.
benchmark-parallel-mirrors-list :
to benchmark mirrors-list in parallel.
scriptinfo : to show script information.
show-packages-busyness <package names> ... :
to show packages are busy or not.
dist-upgrade : to upgrade all packages that is installed.
This subcommand uses setup.exe
update-setup : to update setup.exe
setup [<params> ...] : to call setup.exe
packages-total-count : count number of total packages from setup.ini
packages-total-size [<pattern of section>] :
count size of total packages from setup.ini
packages-cached-count : count number of cached packages
in cache/mirrordir.
packages-cached-size : count size of cached packages
in cache/mirrordir.
repair-acl : repair acl.
source <package names> ... :
download source archive.
mirror-source <package names> ... :
download the source package
into the current cache/mirrordir as mirror.
download <package names> ... :
download the binary package
into the current directory.
mirror <package names> ... :
download the binary package
into the current cache/mirrordir as mirror.
homepage [<package names> ...] :
Open homepages of packages.
web [<package names> ...] :
Synonym for homepage.
listfiles [<package names> ...] :
List files 'owned' by package(s).
get-proxy : Get proxies for eval.
ls-categories : List categories.
ls-pkg-with-category : List packages with category.
category <category> : List all packages in given <category>.
setuprc-get <section> : Get section from 'setup.rc'.
set-cache [<cache>] : Set cache.
set-mirror [<mirrors> ...] :
Set mirror.
Note: setup-x86{,_64}.exe uses all of them
but currently apt-cyg uses the first one only.
mark-auto [<packages> ...] :
Mark the given packages
as automatically installed.
mark-manual [<packages> ...] :
Mark the given packages as manually installed.
mark-showauto : Print the list of
automatically installed packages.
mark-showmanual : Print the list of manually installed packages.
call [<internal_function> [<args> ...]] :
Call internal function in apt-cyg.
time [<internal_function> [<args> ...]] :
Report time consumed
to call internal function in apt-cyg.
filelist [<package>] : File list like apt-file list.
filesearch [<pattern>] : File search like apt-file search.
Options:
--ag : use the silver searcher
(currently work only at packageof subcommand)
--charch <arch> : change architecture
--ignore-case, -i : ignore case distinctions for <patterns>
--force-remove : force remove
--force-fetch-trustedkeys :
force fetch trustedkeys
--force-update-packageof-cache :
force update packageof cache
--no-verify, -X : Don't verify setup.ini signatures
--no-check-certificate : Don't validate the server's certificate
--no-update-setup : Don't update setup.exe
--no-header : Don't print header
--proxy, -p {auto|inherit|none|<url>} :
set proxy (default: \${APT_CYG_PROXY:-auto})
--completion-get-subcommand :
get subcommand (for completion internal use)
--completion-disable-autoupdate :
disable completion autoupdate
--max-jobs, -j <n> : Run <n> jobs in parallel
--mirror, -m <url> : set mirror
--cache, -c <dir> : set cache
--file, -f <file> : read package names from <file>
--noupdate, -u : don't update setup.ini from mirror
--ipv4, -4 : wget prefer ipv4
--no-progress : hide the progress bar in any verbosity mode
--quiet, -q : quiet (no output)
--verbose, -v : verbose
--help : Display help and exit
--version : Display version and exit
EOD
}
function git_status ()
{
local origin status
[ ! -d "${SCRIPT_REALDIR%/}/.git" ] && return 1
pushd "${SCRIPT_REALDIR}" >/dev/null
echo
origin="$(git config --get remote.origin.url)" && echo "origin: $origin"
echo "commit: $(git log -1 --pretty=format:"%ai %h%d")"
status="$(git status --short "${SCRIPT_REALNAME}")"
[ -n "$status" ] && echo "status: $status"
popd >/dev/null
}
function version ()
{
cat<<-EOD
kou1okada/apt-cyg
forked from transcode-open/apt-cyg$(git_status)
This script is based on apt-cyg version 0.57
Copyright (c) 2005-9 Stephen Jungels. Released under the GPL.
Copyright (c) 2013-7 Stephen Jungels. Republished under the MIT license.
EOD
}
# Usage: verbose [level [msg ...]]
function verbose ()
{
(( OPT_VERBOSE_LEVEL < "${1:-1}" )) && return
(( 1 < $# )) && echo "${@:2}" || cat
} >&2
# Usage: verbosefor [level]
function verbosefor ()
{
(( OPT_VERBOSE_LEVEL < ${1:-1} )) && echo /dev/null || echo /dev/stderr
}
function update_verbosefor ()
{
local i
for i in {0..5}; do
(( OPT_VERBOSE_LEVEL < i )) && verbosefor[i]=/dev/null || verbosefor[i]=/dev/stderr
done
}
function detect_field_width ()
# Read stdin and detect field width.
# Return NF+2 values as follorwing:
# w(0) w(1) w(2) ... w(NF) sum(w(1),w(2), ..., w(NF))+NF-1
# Now NF is a number of fields,
# w(x) is a function of maxium width of field x th
# (note that 0 does not mean the field but the whole line)
# and sum(v1,v2, ..., vn) is a function to sum all arguments.
{
awk '
function max(a,b){return a<b?b:a}
{for(i=0;i<=NF;i++)w[i]=max(w[i],length($i));nf=max(nf,NF)}
END{for(i=0;i<=nf;i++){wall+=w[i];printf("%s%d",i?" ":"",w[i])};print " "wall-w[0]+nf-1}
'
}
function align_columns ()
# Read stdin and aligne columns indent.
{
local lines w fmt
readarray -t lines
w=( $(join_str $'\n' "${lines[@]}" | detect_field_width) )
fmt="$(printf " %%-%ds" "${w[@]:1:${#w[@]}-2}")"
printf "${fmt:1}\n" ${lines[@]}
}
function join_str () # <separator> [<strings> ...]
# Join strings with separator.
# Note that separator must be single character.
# If you want separator with multiple character, use join_str_ex.
{
(IFS="$1"; printf "%s" "${*:2}")
}
function join_str_ex () # <separator> [<strings> ...]
# Join strings with separator.
# Different for join_str the separator can take multiple character.
{
local str="$(join_str $'\x1c' "${@:2}")"
printf "%s" "${str//$'\x1c'/$1}"
}
function split_str () # <separator> [<strings> ...]
# Split strings with separator.
{
local str=( "${@:2}" )
(IFS=$'\n'; printf "%s" "${str[*]//$1/$'\n'}")
}
function join_str_uniq () # <separator> [<values> ...]
# Append values to head of joined strings.
{
local str
readarray -t str < <(split_str "$@" | uniqex)
join_str "$1" "${str[@]}"
}
function mkdirp () # <dir>
{
[ -d "$1" ] || mkdir -p "$1" || { error "mkdir failed: $1"; exit 1; }
}
function mktmpfn () # -v <var>
# Temporary filename
{
printf ${@:1:2} "/tmp/${SCRIPT_NAME}.$$.%04x%04x" $RANDOM $RANDOM
}
function init_comspec ()
{
: ${SYSTEMPATH:=$(join_str_uniq : "$(cygpath -u "${SYSTEMROOT:-$WINDIR}")"{/system32,} "$PATH")}
}
function comspec () # [<parameters> ...]
# Call $COMSPEC.
{
init_comspec
PATH="$SYSTEMPATH" "${COMSPEC//\\//}" "$@"
}
function cygstart () # [<parameters> ...]
{
init_comspec
PATH="$SYSTEMPATH" cygstart.exe "$@"
}
function update_cache_for_mirrors_list_online ()
{
pushd "$apt_cyg_cachedir" >/dev/null
wget -qN https://cygwin.com/mirrors.lst
popd >/dev/null
}
function is_official_mirrors_of_cygwin () # <mirrors> ...
# Check <mirrors> whether are listed in official mirrors list of cygwin.
# Official mirros list provides on https://cygwin.com/mirrors.html.
# Args:
# <mirrors> : URLs of the cygwin mirror.
# Return:
# Return zero if all mirrors are known, non-zero otherwise.
{
local mirror
local result=0
local local_list="$(apt-cyg-mirrors-list)"
local online_list="$(apt-cyg-mirrors-list-online)"
for mirror; do
if ! grep -q "$mirror" <<< "$local_list"; then
warning "/etc/setup/setup.rc doesn't know your mirror: ${SGR_bold}$mirror${SGR_reset}" >&2
result=1
fi
if ! grep -q "$mirror" <<< "$online_list"; then
warning "Official mirrors.lst doesn't know your mirror: ${SGR_bold}$mirror${SGR_reset}" >&2
result=1
fi
done
return $result
}
function current_cygarch ()
{
local arch="${HOSTTYPE:-$(arch)}"
echo "${arch/i686/x86}"
}
function mirror_to_mirrordir () # <mirror>
{
local tmp="${1//:/%3a}"
echo "${tmp//\//%2f}"
}
function get_utf8_setuprc ()
{
local utf8_setuprc="$apt_cyg_cachedir/setup.rc.utf8"
mkdirp "$apt_cyg_cachedir"
[ "$utf8_setuprc" -nt /etc/setup/setup.rc ] && {
cat "$utf8_setuprc"
} || {
cp2utf8 /etc/setup/setup.rc | tee "$utf8_setuprc"
}
}
function setuprc_import_sections () # <section> ...
{
local IFS="|"
get_utf8_setuprc \
| awk -vRS='\n\\<|\n\\'\' -vFS='\n\t' -vsections="^${*//\\/\\\\}$" '
match($1, sections) {
s = gensub(/-/, "_", "g", $1) "=("
for(i = 2; i <= NF; i++) s = s " \x27" $i "\x27";
s = s " )";
print s;
}
'
}
function setuprc_get_section () # <section>
{
get_utf8_setuprc \
| awk -vRS='\n\\<|\n\\'\' -vFS='\n\t' -vsection="${1//\\/\\\\}" '
$1 == section {for(i = 2; i <= NF; i++) print $i;}
'
}
function setuprc_set_section () # <section> [<values> ...]
{
local s="$(join_str_ex $'\n\t' "${@}")"
local setuprc="/etc/setup/setup.rc"
local setuprc_bak="${setuprc},$(date -r "$setuprc" "+%Y%m%d_%H%M%S")"
cp -a "$setuprc" "$setuprc_bak"
cp2utf8 "$setuprc_bak" \
| awk -vRS='\n\\<|\n\\'\' -vFS='\n\t' -vsection="${1//\\/\\\\}" -vs="${s//\\/\\\\}" '
$1 != section
$1 == section {print s; done=1;}
END {if(!done) print s;}
' \
| utf82cp > "$setuprc"
}
function set_cachefile () #
# Set filename of cachevars to $cachefile.
# Returns:
# $cachefile : Overwrite with filename of cachevars.
# Note:
# This is internal function for load_vars_from_cache and save_vars_to_cache.
{
cachefile="$apt_cyg_cachedir/cache_for_vars_of_${FUNCNAME[2]}"
}
function load_vars_from_cache () # [<depended files> ...] || { init_vars ...; save_vars_to_cache [<varnames> ...]; }
# restore vars from cache.
{
local cachefile; set_cachefile
local i
set -- "$SCRIPT_PATH" "$@"
for i; do [ "$cachefile" -nt "$i" ] || return 1; done
source "$cachefile"
}
function save_vars_to_cache () # [<varnames> ...]
# save vars to cache.
{
local cachefile; set_cachefile
declare -p "$@" | sed -E 's/^declare .. //g' >"$cachefile"
}
function findworkspace()
{
local cachevars=( last_cache last_mirror mirror cache arch mirrordir )
load_vars_from_cache /etc/setup/setup.rc || {
eval "$(setuprc_import_sections last-cache last-mirror)"
mirror="$last_mirror"
cache="$(cygpath -au "$last_cache")"
arch="$(current_cygarch)"
cache="${cache%/}"
mirror="${mirror%/}"
mirrordir="$(mirror_to_mirrordir "$mirror/")"
save_vars_to_cache "${cachevars[@]}"
}
verbose 1 "Cache directory is $cache"
verbose 1 "Mirror is $mirror"
mkdirp "$cache/$mirrordir/$arch"
cd "$cache/$mirrordir/$arch"
init_gnupg
fetch_trustedkeys
}
function download_and_verify () # <url>
{
local urls=( "$1"{,.sig} )
wget -N "${urls[@]}" || return 1
if [ -z "$no_verify" ]; then
[ -e "${1##*/}.sig" ] && verify_signatures "${1##*/}.sig" || return 1
fi
[ -e "${1##*/}" ]
}
function files_backup ()
{
local file
for file; do
[ -e "${file}~" ] && mv "${file}~" "${file}"
[ -e "${file}" ] && cp -a "${file}" "${file}~"
done
}
function files_restore ()
{
local file
for file; do
[ -e "${file}" ] && rm "${file}"
[ -e "${file}~" ] && mv "${file}~" "${file}"
done
}
function files_backup_clean ()
{
local file
for file; do
[ -e "${file}~" ] && rm "${file}~"
done
}
function setupini_download ()
{
local BASEDIR="$cache/$mirrordir/$arch"
mkdirp "$BASEDIR"
[ $noscripts -ne 0 -o $noupdate -ne 0 ] && return
pushd "$BASEDIR" > /dev/null
files_backup setup.ini setup.ini.sig setup.bz2 setup.bz2.sig
while true; do
verbose 1 "Updating setup.ini"
download_and_verify "$mirror/$arch/setup.bz2" && { bunzip2 -k setup.bz2 && mv setup setup.ini || rm -f setup.bz2; }
download_and_verify "$mirror/$arch/setup.ini" || break
files_backup_clean setup.ini setup.ini.sig setup.bz2 setup.bz2.sig
popd > /dev/null
verbose 1 "Updated setup.ini"
return
done
files_restore setup.ini setup.ini.sig setup.bz2 setup.bz2.sig
popd > /dev/null
error "updating setup.ini failed, reverting."
return 1
}
function getsetup ()
{
setupini_download || return 1
}
function checkpackages()
{
if [ $# -eq 0 ]; then
echo Nothing to do, exiting
exit 0
fi
}
# Usage: getrootdir arch
function getrootdir ()
{
case "$1" in
x86)
cygpath -u "$(< /proc/registry32/HKEY_LOCAL_MACHINE/SOFTWARE/Cygwin/setup/rootdir)" ;;
x86_64)
cygpath -u "$(< /proc/registry64/HKEY_LOCAL_MACHINE/SOFTWARE/Cygwin/setup/rootdir)" ;;
*)
error "unknown arch: $1" ;;
esac
}
# Usage: charch arch apt-cyg_parms ...
function charch ()
{
local rootdir
if [ "$(current_cygarch)" != "$1" ]; then
echo -e "${SGR_fg_green}${SGR_bold}charch to:${SGR_reset} $1"
rootdir="$(getrootdir "$1")"
shift
chroot "$rootdir" "$rootdir/bin/bash" -lc \
'cd "$1"; shift ; "$0" "$@"' \
"$(type -p "$0" | xargs cygpath -aml | xargs cygpath -u)" \
"$(pwd | xargs cygpath -aml | xargs cygpath -u)" \
"$@"
exit $?
fi
}
function init_gnupg ()
{
[ -z "$GPG" -o -n "$no_verify" ] && return
export GNUPGHOME="$cache/.apt-cyg"
if [ ! -d "$GNUPGHOME" ]; then
if ! { mkdir -p "$GNUPGHOME" && chmod 700 "$GNUPGHOME"; } then
error "Cannot initialize directory: $GNUPGHOME"
exit 1
fi
fi
}
# Usage: ask_user [MESSAGE [OPTIONS]]
function ask_user ()
{
local answer retcode option
local MESSAGE="$1"
local OPTIONS="${2:-y/N}"
local DEFAULT="$(echo "$OPTIONS" | awk -v FS=/ '{for(i=1;i<=NF;i++)if(match(substr($i,1,1),/[A-Z]/)){print $i; exit}}')"
local SPLIT_OPTIONS
readarray -t SPLIT_OPTIONS < <(echo "$OPTIONS" | sed -e 's:/:\n:g')
while true; do
echo -n "${MESSAGE}${MESSAGE:+ }[${OPTIONS}] "
read answer
retcode=0
for option in "${SPLIT_OPTIONS[@]}"; do
if [ "$option" = "${answer:-$DEFAULT}" ]; then
return $retcode
fi
retcode=$(( retcode + 1 ))
done
done
}
unset INIT_WGET
function init_wget ()
{
[ -n "$INIT_WGET" ] && return
eval "$(
"$WGET" --help \
|& awk '
/--show-progres/{print "HAVE_SHOW_PROGRESS=--show-progress"}
/--no-verbose/ {print "HAVE_NO_VERBOSE=--no-verbose"}
')"
(( OPT_VERBOSE_LEVEL < 0 )) && WGET+=( --quiet ) || \
(( OPT_VERBOSE_LEVEL < 1 )) && WGET+=( --quiet $HAVE_SHOW_PROGRESS ) || \
(( OPT_VERBOSE_LEVEL < 2 )) && WGET+=( $HAVE_NO_VERBOSE $HAVE_SHOW_PROGRESS )
proxy_setup
INIT_WGET=DONE
}
function wget ()
{
init_wget
"${WGET[@]}" "$@"
}
# Reference:
# https://www.gnu.org/software/wget/manual/wget.html#Exit-Status
# Usage: wget-exitstatus EXITSTATUS
function wget-exitstatus ()
{
case $1 in
0) echo "No problems occurred.";;
1) echo "Generic error code.";;
2) echo "Parse error?for instance, when parsing command-line options, the '.wgetrc' or '.netrc'...";;
3) echo "File I/O error.";;
4) echo "Network failure.";;
5) echo "SSL verification failure.";;
6) echo "Username/password authentication failure.";;
7) echo "Protocol errors.";;
8) echo "Server issued an error response.";;
*) echo "Unknown errors.";;
esac
}
function wget_advice ()
{
local status=${1:-$?}
case $status in
5) echo "If you can tolerate security risks, use --no-certification option." ;;
esac
return $status
}
# Usage: get_advice cmd
function get_advice ()
{
local status=${2:-$?}
type "${1}_advice" >&/dev/nul && { ( exit $status ); "${1}_advice"; }
return $status
}
# Usage: push_advice cmd
function push_advice ()
{
local status=${2:-$?}
ADVICE+=( "$( get_advice "${1}_advice")" )
return $status
}
function show_advice ()
{
local i
for i in "${ADVICE[@]}"; do
echo "$i" >&2
done
}
# Usage: wget_and_hash_check label hash url file
function wget_and_hash_check ()
{
local LABEL="$1"
local SUM="$2"
local URL="$3"
local FILE="$4"
if ! { wget "$URL" -O "$FILE" || get_advice wget; }; then
echo "$LABEL: FAILED: Could not download $URL."
return 1
fi
if ! hash_check <<<"$SUM *$FILE" >&/dev/null; then
echo "$LABEL: FAILED: Hash does not match $URL."
return 2
fi
echo "$LABEL: OK"
}
function get_gpg_fingerprint_to_assoc () # <assoc varname>
{
local -n result="$1"
local line lines
readarray -t lines < <("${GPG[@]}" --with-colons --fingerprint)
for line in "${lines[@]}"; do
[[ "$line" =~ ^fpr:+([0-9A-Za-z]+):* ]] && result[${BASH_REMATCH[1]}]=1
done
}
function fetch_trustedkeys ()
{
[ -z "$GPG" -o -n "$no_verify" ] && return
local i
local FILE ; mktmpfn -v FILE
local FILE_LATEST; mktmpfn -v FILE_LATEST
local -A FPRS_assoc; get_gpg_fingerprint_to_assoc FPRS_assoc
for i in "${TRUSTEDKEYS[@]}"; do
local LABEL="TRUSTEDKEY_${i}"
local -n SUM="${LABEL}_SUM"
local -n FPR="${LABEL}_FPR"
local -n URL="${LABEL}_URL"
local -n URL_LATEST="${LABEL}_URL_LATEST"
local CASE=""
if [ -z "$force_fetch_trustedkeys" -a -n "${FPRS_assoc[$FPR]}" ]; then
continue
fi
if [ -n "$URL" ]; then
wget_and_hash_check "$LABEL" "$SUM" "$URL" "$FILE"
CASE+="$?"
else
CASE+="-"
fi
if [ -n "$URL_LATEST" ]; then
wget_and_hash_check "$LABEL" "$SUM" "$URL_LATEST" "$FILE_LATEST"
CASE+="$?"
else
CASE+="-"
fi
case "$CASE" in
00|01|0-)
"${GPG[@]}" --import "$FILE"
;;
02)
warning "${LABEL} has been updated."
"${GPG[@]}" --import "$FILE"
;;
-0)
"${GPG[@]}" --import "$FILE_LATEST"
;;
10|20)
error "${LABEL} has miss configuration."
exit 1
;;
11|1-|-1)
error "Could not download ${LABEL}."
exit 1
;;
12|-2)
error "${LABEL} has been updated, maybe. But sometimes it may has been cracked. Be careful !!!"
exit 1
;;
21|22|2-)
error "${LABEL} has been cracked, maybe"
exit 1
;;
--)
error "${LABEL} has no URL."
exit 1
;;
esac
rm "$FILE" "$FILE_LATEST" &>/dev/null
done
}
# Usage: verify_signatures files ...
function verify_signatures ()
{
while [ $# -gt 0 ]; do
if ! "${GPG[@]}" --verify "$1" &>"${verbosefor[2]}"; then
error "BAD signature: $1"
return 1
else
verbose 0 -e "${SGR_fg_green}${SGR_bold}signature verified:${SGR_reset} $1"
fi
shift
done
}
# Usage: apt-cyg-key-add pkey ...
function apt-cyg-key-add ()
{
[ -z "$GPG" ] && { error "GnuPG is not installed. Prease install gnupg package"; exit 1; }
local pkeys
for pkey; do
pkeys+=( "$(cygpath -a "$pkey" )" )
done
findworkspace
for pkey in "${pkeys[@]}"; do
"${GPG[@]}" --import "$pkey"
done
}
# Usage: apt-cyg-key-add keyid ...
function apt-cyg-key-del ()
{
[ -z "$GPG" ] && { error "GnuPG is not installed. Prease install gnupg package"; exit 1; }
local keyid
findworkspace
for keyid; do
"${GPG[@]}" --batch --yes --delete-key "$keyid"
done
}
function apt-cyg-key-list ()
{
[ -z "$GPG" ] && { error "GnuPG is not installed. Prease install gnupg package"; exit 1; }
findworkspace
"${GPG[@]}" --list-keys
}
function apt-cyg-key-finger ()
{
[ -z "$GPG" ] && { error "GnuPG is not installed. Prease install gnupg package"; exit 1; }
findworkspace
"${GPG[@]}" --fingerprint
}
function apt-cyg-pathof ()
{
findworkspace >& /dev/null
while [ "$#" -gt 0 ]; do
case "$1" in
cache) echo "$cache" ;;
mirror) echo "$mirror" ;;
mirrordir) echo "$mirrordir" ;;
cache/mirrordir) echo "$cache/$mirrordir" ;;
setup.ini) echo "$cache/$mirrordir/$arch/setup.ini" ;;
*)
error "unknown parameter: $1"
exit 1
;;
esac
shift
done
}
function upgrade-self-with-git ()
{
if [ ! -d "$SCRIPT_REALDIR/.git" ]; then
warning "apt-cyg is not under the git version control."
return 1
fi
pushd "$SCRIPT_REALDIR" > /dev/null
git pull -v
popd > /dev/null
}
function upgrade-self-with-wget ()
{
local updated_url='https://raw.githubusercontent.com/kou1okada/apt-cyg/master/apt-cyg' # TODO: Do not use MAGIC NUMBER
local temp_file; mktmpfn -v temp_file
wget "${updated_url}" -q -O "$temp_file"
chmod +x "$temp_file"
{ diff "$temp_file" "$SCRIPT_REALPATH" >/dev/null && exit 0; } || cp "$temp_file" "$SCRIPT_REALPATH"
rm "$temp_file"
}
function apt-cyg-upgrade-self ()
{
upgrade-self-with-git && return
echo "Fall back to wget for upgrade-self."
upgrade-self-with-wget
}
function proxy_auto ()
{
local hash=( $(ipconfig |& md5sum -b) )
local cache="/tmp/apt-cyg.proxy.$hash"
local last="$(stat -c %Y "$cache" 2>/dev/null)"
local now="$(printf "%(%s)T")"
local proxy
[ -n "$OPT_PROXY_FORCE_REFRESH" ] && last=0
if (( (now - ${last:-0}) < OPT_PROXY_REFRESH_INTERVAL )); then