]> git.donarmstrong.com Git - neurodebian.git/blob - tools/nd-aptenable
ENH: Allow to pass config via environment, install needed packages (if --install...
[neurodebian.git] / tools / nd-aptenable
1 #!/bin/bash
2 #emacs: -*- mode: shell-script; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
3 #ex: set sts=4 ts=4 sw=4 et:
4
5 # Depends:    apt (assumed to be present), python, wget
6 # Recommends: netselect
7
8 # play safe
9 set -e
10 set -u
11
12 ############
13 # Defaults #
14 ############
15
16 nd_aptenable_version=0.1
17
18 nd_key_id=0x2649A5A9
19 nd_config_url=https://raw.githubusercontent.com/neurodebian/neurodebian/master/neurodebian.cfg
20 nd_config_file=/etc/neurodebian/neurodebian.cfg
21 nd_mirror_origin=http://neuro.debian.net/debian
22 nd_mirror_default=$nd_mirror_origin # or may be AWS?
23
24 # To be set by cmdline args or via env variables with prefix ND_AE_
25 ae_release=${ND_AE_RELEASE:-}
26 ae_components=${ND_AE_COMPONENTS:-software,data}
27 ae_flavor=${ND_AE_FLAVOR:-}
28 ae_mirror=${ND_AE_MIRROR:-best}
29 ae_suffix=${ND_AE_SUFFIX:-}
30 ae_verbose=${ND_AE_VERBOSE:-1}
31 ae_overwrite=${ND_AE_OVERWRITE:-}
32 ae_sources=${ND_AE_SOURCES:-}
33 ae_install=${ND_AE_INSTALL:-}
34 ae_dry_run=${ND_AE_DRY_RUN:-}
35 ae_defun_only=${ND_AE_DEFUN_ONLY:-} # mode to source this file as a "library"
36
37 ae_sudo=
38 exe_dir=$(dirname $0)
39
40 # TODOs:
41 # - apt priority! (so we could avoid automagic upgrades etc)
42 # - multiarch setups
43
44 ae_tempdir=$(mktemp -d)
45 trap "rm -rf \"$ae_tempdir\"" TERM INT EXIT
46
47
48 print_verbose()
49 {
50     level=$1; shift
51         if [ "$ae_verbose" -ge $level ]; then
52         # use stderr for printing within functions stdout of which might be used
53         echo -n "I: " >&2
54         i=1; while [ $i -lt $level ]; do echo -ne " ">&2; i=$(($i+1)); done
55         echo -e "$*" >&2
56     fi
57 }
58
59 error()
60 {
61     code=$1; shift
62         echo -e "E: $*" >&2
63     exit $code
64 }
65
66 print_version()
67 {
68     cat << EOT
69 nd-aptenable $nd_aptenable_version
70
71 Copyright (C) 2014 Yaroslav Halchenko <debian@onerussian.com>
72
73 Licensed under GNU Public License version 3 or later.
74 This is free software; see the source for copying conditions.  There is NO
75 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
76
77 Written by Yaroslav Halchenko for the NeuroDebian project.
78
79 EOT
80 }
81
82 eval_dry()
83 {
84     if [ -z "$ae_dry_run" ]; then
85         if eval "$ae_sudo $@" 1>|"$ae_tempdir/eval.log" 2>&1; then
86             rm "$ae_tempdir/eval.log"
87         else
88             error $? "Command $@ failed with exit code $?.  Output was: `cat $ae_tempdir/eval.log`"
89         fi
90     else
91         echo "DRY: $@" >&2
92     fi
93 }
94
95 print_help()
96 {
97     cat << EOT
98
99 Usage:  nd-aptenable [options]
100
101 Enables NeuroDebian repository for the current Debian or Ubuntu release.
102
103 Options:
104
105   -r, --release=RELEASE
106     Name of the Debian/Ubuntu release to be used.  If not specified,
107     it is deduced from the  apt-cache policy  output, by taking repository
108     of Debian or Ubuntu origin with highest priority.
109
110   -f, --flavor=full|libre
111     Which flavor of the repository should be enabled:
112      libre -- Only  main  component, containing only DFSG-compliant content.
113      full -- Includes main, contrib, and non-free.
114     If not specified -- deduced from the output of apt-cache policy
115
116   -c, --components=c1,c2,c3
117     Comma separated list of components to enable among:
118      software -- primary software repository
119      data -- data packages
120      devel -- "overlay" of development versions (like Debians' "experimental").
121               Not sufficient on its own and available only from the main site
122     If not specified -- "software,data"
123
124   -m, --mirror=NAME|URL
125     Which mirror to use.  Could be a mirror code-name (as specified in
126     /etc/neurodebian/neurodebian.cfg), or a URL.
127
128   --overwrite,
129     If apt file already present, it would not be overriden (by default).
130     Use this option to overwrite.
131
132   --suffix=SUFFIX
133     Which suffix to add to the apt file, in case you are trying to enable
134     multiple repositories
135
136   --sources, --no-sources
137     Either to enable deb-src lines.  If none specified -- would be enabled if
138     sources for a core package (apt) are available.
139
140   -n, --dry-run
141     Do not perform any changes -- generated configurations and commands will
142     simply be printed to stdout
143
144   --install
145     If found absent, all necessary tools (wget, netselect) if available will
146     be apt-get installed
147
148   -v, --verbose
149     Enable additional progress messages.  Could be used multiple times
150
151   -q, --quiet
152     Make operation quiet -- only error messages would be output
153
154   -h, --help
155     Print short description, usage summary and option list.
156
157   --version
158     Print version information and exit.
159
160 Exit status:
161
162   non-0 exit status in case of error.  Error exit code would depend
163   on which command has failed
164
165 Examples:
166
167   - Enable software and data components from the optimal (according to
168     netselect) mirror.  Some information about progress will be printed
169
170     nd-aptenable
171
172   - Quietly enable -devel repository for the current release, and place apt
173     configuration into /etc/apt/sources.list.d/neurodebian.sources-devel.list
174
175     nd-aptenable -q --suffix=-devel -c devel
176
177   - Force sid distribution, all the components, from the Japan mirror:
178
179     nd-aptenable -q --suffix=-de-sid-full -c software,data,devel -m jp
180
181 EOT
182 }
183
184 get_neurodebian_cfg()
185 {
186     # First we try to fetch the most recent version from the github
187     print_verbose 3 "Fetching config file from the github repository"
188     cfgfile_temp="$ae_tempdir/neurodebian.cfg"
189     assure_command_from_package wget wget 1
190     wget --no-check-certificate -c -q -O$cfgfile_temp \
191         $nd_config_url \
192         && { echo $cfgfile_temp; } \
193         || { [ -e "$nd_config_file" ] \
194              && echo "$nd_config_file" \
195              || error 10 "Neither could fetch $nd_config_url, nor found $nd_config_file"; }
196 }
197
198 query_cfg_section()
199 {
200     config_file="$1"
201     section="$2"
202     print_verbose 3 "Querying config $config_file section $section"
203     assure_command_from_package python python-minimal 1
204     python -c "from ConfigParser import SafeConfigParser as SP; cfg = SP(); cfg.read('$config_file'); print('\n'.join([' '.join(x) for x in cfg.items('$section')]))"
205 }
206
207 get_mirrors()
208 {
209     nd_config=`get_neurodebian_cfg`
210 #    $exe_dir/nd_querycfg -F" " --config-file="$nd_config" "mirrors" \
211     query_cfg_section "$nd_config" "mirrors" \
212     | while read mirror_name mirror_url; do
213         # verify that url is just a url
214         if echo "$mirror_url" | grep -v -e '^[a-z0-9:+]*://[-+_%.a-z0-9/]*$'; then
215             print_verbose 1 "Mirror $mirror_name has 'illegit' URL: $mirror_url.  Skipping"
216         fi
217         echo "$mirror_name $mirror_url"
218     done
219 }
220
221 netselect_mirror() {
222     # select "closest" mirror according to netselect.
223     print_verbose 2 "Selecting the 'best' mirror using netselect"
224     assure_command_from_package netselect
225     if ! which netselect >&/dev/null; then
226         print_verbose 1 "netselect (apt-get install netselect) needed to select the 'best' mirror was not found"
227         print_verbose 1 "Selecting the default repository: $nd_mirror_default"
228         echo $nd_mirror_default
229     else
230         best_mirror=$(get_mirrors | awk '{print $2;}' | $ae_sudo xargs netselect -D -s 1 | awk '{print $2;}')
231         print_verbose 2 "Best mirror: $best_mirror"
232         echo $best_mirror
233     fi
234 }
235
236 get_mirror_url()
237 {
238     # given mirror alias -- find its url
239     url=$(get_mirrors | awk "/^$1 /{print \$2;}")
240     if [ -z "$url" ]; then
241         error 9 "Cannot resolve mirror $1 to the URL"
242     fi
243     echo $url
244 }
245
246 get_apt_policy()
247 {
248     # Get apt-cache policy output in a single list for matching suites
249     # (could be a separated with \| or , for multiple choices, e.g.
250     #
251     # get_apt_policy Debian,Ubuntu
252     # or
253     # get_apt_policy NeuroDebian
254     suites="$1"
255     $ae_sudo apt-cache policy | grep -B1 -e "o=\(${suites//,/\\|}\)" | tr '\n' ' ' | sed -e 's, -- ,\n,g' | grep -v -e '-\(updates\|security\)' | sort -nr
256 }
257
258 is_component_included()
259 {
260     echo "$ae_components" | tr ',' '\n' | grep -q "^$1\$"
261 }
262
263 is_sources_enabled()
264 {
265     apt-cache showsrc apt >&/dev/null && echo 1 || echo 0
266 }
267
268 assure_command_from_package()
269 {
270     cmd=$1
271     pkg=${2:-$cmd}
272     fail=${3:-}
273
274     which "$cmd" >&/dev/null && return 0
275
276     # if absent -- check availability of the package
277     apt_cache=$(LANG=C apt-cache policy "$pkg" 2>&1)
278     if [[ "$apt_cache" =~ "Unable to locate package" ]] || [[ "$apt_cache" =~ "Candidate: (none)" ]]; then
279         print_verbose 1 "Package $pkg providing command $cmd is N/A. Skipping"
280         return 10;
281     fi
282     if echo "$apt_cache" | grep -q '^\s*\*\*\*'; then
283         print_verbose 1 "WARNING -- command $cmd is N/A but package $pkg is claimed to be installed"
284         [ -z "$fail" ] && return 11 || error $fail "Command $cmd is required to proceed"
285     fi
286     if [ "$ae_install" = "1" ]; then
287         print_verbose 1 "Installing $pkg package to get $cmd command"
288         eval_dry DEBIAN_FRONTEND=noninteractive apt-get install -y "$pkg"
289         return
290     else
291         print_verbose 1 "Command $cmd (from package $pkg) is N/A."
292         print_verbose 1 "Use with --install to get all necessary packages installed automatically"
293         [ -z "$fail" ] && return 12 || error $fail "Command $cmd is required to proceed"
294     fi
295 }
296
297 # if it was requested -- return without doing anything
298 [ -z "$ae_defun_only" ] || return
299
300 #
301 # Commandline options handling
302 #
303
304 # Parse commandline options (taken from the getopt examples from the Debian util-linux package)
305 # Note that we use `"$@"' to let each command-line parameter expand to a
306 # separate word. The quotes around `$@' are essential!
307 # We need CLOPTS as the `eval set --' would nuke the return value of getopt.
308 CLOPTS=`getopt -o h,r:,m:,f:,c:,q,v,n --long help,version,quiet,verbose,mirror:,release:,flavor:,components:,suffix:,overwrite,sources,no-sources,install,dry-run,print-mirrors,print-best-mirror -n 'nd-aptenable' -- "$@"`
309
310 if [ $? != 0 ] ; then
311   error 2 "Problem with parsing cmdline.  Terminating..."
312 fi
313
314 # Note the quotes around `$CLOPTS': they are essential!
315 eval set -- "$CLOPTS"
316
317 if [ `whoami` != "root" ]; then
318     ae_sudo=sudo
319 fi
320
321 while true ; do
322   case "$1" in
323           -r|--release) shift; ae_release="$1"; shift;;
324           -f|--flavor) shift;  ae_flavor="$1"; shift;;
325           -c|--components) shift; ae_components="$1"; shift;;
326       -m|--mirror) shift;  ae_mirror="$1"; shift;;
327          --print-mirrors)  get_mirrors; exit 0;;
328          --print-best-mirror)  netselect_mirror; exit 0;;
329       -n|--dry-run)        ae_dry_run=1; shift;;
330          --suffix) shift;  ae_suffix="$1"; shift;;
331          --overwrite)      ae_overwrite="$1"; shift;;
332          --sources)        ae_sources=1; shift;;
333          --no-sources)     ae_sources=0; shift;;
334          --install)        ae_install=1; shift;;
335           -q|--quiet)          ae_verbose=0; shift;;
336           -v|--verbose)        ae_verbose=$(($ae_verbose+1)); shift;;
337           -h|--help) print_help; exit 0;;
338           --version) print_version; exit 0;;
339           --) shift ; break ;;
340           *) error 1 "Internal error! ($1)";;
341   esac
342 done
343
344
345 if [ $# -gt 0 ] ; then
346     print_help >&2
347     exit 2
348 fi
349
350 # Inform!
351 [ -z "$ae_sudo" ] || print_verbose 1 "This script requires root access.  Since current user is not root, sudo will be used"
352
353 #
354 # Basic system/environment knowledge
355 #
356
357 ae_output_file=/etc/apt/sources.list.d/neurodebian.sources${ae_suffix}.list
358
359 apt_policy=$(get_apt_policy "Debian,Ubuntu" )
360
361 if [ -z "$ae_release" ]; then
362     ae_release=$(echo "$apt_policy" | head -1 | sed -e 's/.*,n=\([^,]*\),.*/\1/g')
363 fi
364
365 if [ -z "$ae_flavor" ]; then
366     ae_flavor=$(echo "$apt_policy" | grep -e ",n=$ae_release," | grep -qe 'c=\(non-free\|restricted\)' && echo "full" || echo "libre")
367 fi
368
369 #
370 # Determine which mirror to use
371 #
372
373 # knowing mirror is not necessary for -devel available only from the main site
374 if is_component_included software || is_component_included data; then
375     # for now just use default
376     if [ -z "$ae_mirror" ]; then # none specified
377         ae_mirror_url=$nd_mirror_origin
378     else
379         if ! [[ "$ae_mirror" =~ ".*://.*" ]]; then
380             case "$ae_mirror" in
381                 best)    ae_mirror_url=$(netselect_mirror);;
382                 default) ae_mirror_url=$nd_mirror_default;;
383                 origin)  ae_mirror_url=$nd_mirror_origin;;
384                 *)       ae_mirror_url=$(get_mirror_url "$ae_mirror");;
385             esac
386         else
387             ae_mirror_url="$ae_mirror" # it was some kind of a URL already
388         fi
389     fi
390 fi
391
392 #
393 # Prepare APT file
394 #
395
396 case $ae_flavor in
397  full)  apt_flavor="contrib non-free";;
398  libre) apt_flavor="";;
399  *) error 5 "Unknown value of flavor $apt_flavor.  Must be full or libre"
400 esac
401
402 if [ -z "$ae_sources" ]; then
403     ae_sources=$(is_sources_enabled)
404 fi
405
406 if [ $ae_sources -eq 0 ]; then
407     sources_comment="#"
408 else
409     sources_comment=""
410 fi
411
412 apt_list=
413
414 if is_component_included software; then
415     apt_list+="
416 # NeuroDebian software repository
417 deb     $ae_mirror_url $ae_release main $apt_flavor
418 ${sources_comment}deb-src $ae_mirror_url $ae_release main $apt_flavor
419 "
420 fi
421
422 if is_component_included data; then
423     apt_list+="
424 # NeuroDebian data repository
425 deb     $ae_mirror_url data main $apt_flavor
426 ${sources_comment}deb-src $ae_mirror_url data main $apt_flavor
427 "
428 fi
429
430 if is_component_included devel; then
431     apt_list+="
432 # NeuroDebian -devel repository
433 deb     http://neuro.debian.net/debian-devel $ae_release main $apt_flavor
434 ${sources_comment}deb-src http://neuro.debian.net/debian-devel $ae_release main $apt_flavor
435 "
436 fi
437
438 if [ -e "$ae_output_file" ] && [ -z "$ae_overwrite" ]; then
439     if diff "$ae_output_file" <(echo "$apt_list") | grep -q .; then
440         # error 3
441         print_verbose 1 "File $ae_output_file already exists, containing:\n`cat \"$ae_output_file\"`\n\nI: New configuration is different:\n$apt_list"
442         if get_apt_policy NeuroDebian >/dev/null; then
443             print_verbose 1 "NeuroDebian repositories are already available, thus skipping the rest."
444             print_verbose 1 "Rerun with --overwrite if you would like to reconfigure."
445             exit 0
446         else
447             print_verbose 1 "NeuroDebian configuration is found but not yet available -- continuing with new configuration."
448         fi
449     else
450         print_verbose 1 "New configuration is identical to existing and NeuroDebian repository is already enabled."
451         print_verbose 1 "Skiping the rest. Rerun with --overwrite if you would like to reconfigure."
452         exit 0
453     fi
454 else
455     print_verbose 1 "Generating $ae_output_file"
456     if [ -z "$ae_dry_run" ]; then
457         echo "$apt_list" | $ae_sudo bash -c "cat - >| '$ae_output_file'"
458     else
459         echo "DRY:"
460         echo "$apt_list"
461     fi
462 fi
463
464
465 #
466 # Assure present archive GPG key for APT system
467 #
468
469 # Figure out if key needs to be imported (if ran within package,
470 # should already be there due to neurodebian-keyring package)
471 if LANG=C eval $ae_sudo apt-key export $nd_key_id 2>&1 1>/dev/null | grep -qe "nothing exported"; then
472     print_verbose 1 "Fetching the key from the server"
473     eval_dry apt-key adv --recv-keys --keyserver pgp.mit.edu $nd_key_id
474 fi
475
476
477 #
478 # Finalizing (apt-get update etc)
479 #
480
481 print_verbose 1 "Updating APT listings, might take a few minutes"
482 if [ -z "$ae_dry_run" ]; then
483     apt_logfile="$ae_tempdir/apt.log"
484     $ae_sudo apt-get update 1>"$apt_logfile" 2>&1 \
485         && rm -f "$apt_logfile" \
486         || {
487              cat "$apt_logfile"
488              error 5 "E: Update failed with exit code $? (above output logged into $apt_logfile)."
489              }
490 else
491     eval_dry apt-get update
492 fi
493
494 if [ "$ae_verbose" -ge 2 ]; then
495     print_verbose 2 "Currently enabled NeuroDebian suites/mirrors:"
496     get_apt_policy NeuroDebian
497 fi