summaryrefslogtreecommitdiff
path: root/src/chroot-tools/librechroot
blob: cd814ee62c712547b275552014bc96a58a3a4c2e (plain)
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
#!/usr/bin/env bash

# librechroot - create, manage, and maintain libre chroots
#
# Copyright (C) 2010-2012           Nicolás Reynolds <fauno@parabola.nu>
# Copyright (C) 2011-2012           Joshua Ismael Haase Hernández (xihh) <hahj87@gmail.com>
# Copyright (C) 2012                Michał Masłowski <mtjm@mtjm.eu>
# Copyright (C) 2012-2018           Luke Shumaker <lukeshu@parabola.nu>
# Copyright (C) 2018                Andreas Grapentin <andreas@grapentin.org>
# Copyright (C) 2019,2020,2022-2023 bill-auger <bill-auger@programmer.net>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This file is part of Parabola Libretools.
#
# Parabola is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Parabola is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Parabola. If not, see <http://www.gnu.org/licenses/>.

# HACKING: if a command is added or removed, take special notice of:
#   - the usage() text
#   - the COMMANDS=() array
#   - the the "validate CLI options" switch block which validates them
#   - the "handle commands" switch block which handles them


source "$(librelib conf                )" # defines $BASE_PKGS, $CHROOT_CONF
                                          # defines $LIBRETOOLS_CONF_SH
                                          # defines $PACMAN_DEFS_DIR, $SUPPORTED_ARCHES
                                          # implements base_pkgs()
source "$(librelib messages            )"
source "$(librelib chroot/makechrootpkg)"


set -euE
shopt -s nullglob
umask 0022


################################################################################
# Utility functions                                                            #
################################################################################

# Usage: detect_chroot_arch $makepkg_conf
detect_chroot_arch()
(
  local makepkg_conf="$1"
  local arches_rx="^($(sed 's/ /|/g' <<< ${SUPPORTED_ARCHES[*]}))$"

  unset CARCH ; source "$makepkg_conf" &> /dev/null ;
  if [[ "$CARCH" =~ $arches_rx ]]; then
    echo $CARCH
  else
    error 'Invalid makepkg.conf: %s' "$makepkg_conf"
    return $EXIT_MISCONFIGURED
  fi
)

# Usage: make_empty_repo $copydir
make_empty_repo() {
  local copydir=$1

  mkdir -p "${copydir}/repo"
  bsdtar -czf "${copydir}/repo/repo.db.tar.gz" -T /dev/null
  ln -s "repo.db.tar.gz" "${copydir}/repo/repo.db"
}

# Usage: chroot_add_to_local_repo $copydir $pkgfiles...
chroot_add_to_local_repo() {
  local copydir=$1; shift
  local pkgfile

  mkdir -p "$copydir/repo"
  for pkgfile in "$@"; do
    cp "$pkgfile" "$copydir/repo"
    pushd "$copydir/repo" >/dev/null
    repo-add repo.db.tar.gz "${pkgfile##*/}"
    popd >/dev/null
  done
}

# Print code to set $rootdir and $copydir; blank them on error
calculate_directories() {
  # Don't assume that CHROOTDIR or CHROOT are set,
  # but assume that COPY is set.
  local rootdir copydir

  # TODO: review the implementation and USAGE for `-l`
  #       this trick only works with absolute path to chroot
  #       eg: why does `-l` accept 'Name of, or absolute path ...'
  #           when -n can be given for 'Name of the chroot to use'?
  if [[ ${COPY:0:1} = / ]]; then
    CHROOTDIR=$(dirname  $(dirname ${COPY}))
    CHROOT=$(   basename $(dirname ${COPY}))
  fi

  if [[ -n ${CHROOTDIR:-} ]] && [[ -n ${CHROOT:-} ]]; then
    rootdir="${CHROOTDIR}/${CHROOT}/root"
  else
    rootdir=''
  fi

  if [[ ${COPY:0:1} = / ]]; then
    copydir=$COPY
  elif [[ -n ${CHROOTDIR:-} ]] && [[ -n ${CHROOT:-} ]]; then
    copydir="${CHROOTDIR}/${CHROOT}/${COPY}"
  else
    copydir=''
  fi

  declare -p CHROOTDIR
  declare -p CHROOT
  declare -p rootdir
  declare -p copydir
}

check_mountpoint() {
  local file=$1
  local mountpoint mountopts

  mountpoint="$(df -P "$file"|sed '1d;s/.*\s//')"
  mountopts=($(LC_ALL=C mount|awk "{ if (\$3==\"$mountpoint\") { gsub(/[(,)]/, \" \", \$6); print \$6 } }"))
  ! in_array nosuid "${mountopts[@]}" && ! in_array noexec "${mountopts[@]}"
}


################################################################################
# Wrappers for files in ${pkglibexecdir}/chroot/                               #
################################################################################

readonly ChrootRun="$( librelib chroot/chroot-run)"
readonly Mkarchroot="$(librelib chroot/mkarchroot)"

ChrootRunFlags=()
MkarchrootFlags=()

hack_mkarchroot_flags() {
  # process and modify local caller copy of $mkarchroot_flags
  local copydir="$1"
  local makepkg_conf="$copydir/etc/makepkg.conf"
  local CARCH setarch interpreter binfmt_cfg

  OPTIND=1
  set -- "${mkarchroot_flags[@]}"
  while getopts 'hC:M:c:f:s' arg; do
    case "$arg" in
      M) makepkg_conf="$OPTARG" ;;
      *) :                      ;;
    esac
  done

  CARCH=$(detect_chroot_arch "$makepkg_conf")
  case $CARCH in
    armv7h|armv7l) setarch=armv7l ; interpreter=/usr/bin/qemu-arm-static    ;;
    *)             setarch=$CARCH ; interpreter=/usr/bin/qemu-$CARCH-static ;;
  esac
  if ! setarch $setarch /bin/true 2>/dev/null; then
    # We're running a cross-arch chroot
    # Make sure that qemu-static is set up with binfmt_misc
    binfmt_cfg=$(grep -l -xF                                      \
                      -e "interpreter $interpreter"               \
                      -r -- /proc/sys/fs/binfmt_misc 2> /dev/null |
                 xargs -r grep -xF 'enabled'                      )
    if [[ -z "$binfmt_cfg" ]]
    then
      error 'Cannot cross-compile for %s on %s' "$CARCH" "$(uname -m)"
      plain 'This requires a binfmt_misc entry for %s.' "$interpreter"
      prose 'Such a binfmt_misc entry is provided by the %s
             package.  If you have it installed, but still see
             this message, you may need to restart %s.' \
            qemu-user-static-binfmt binfmt
      return $EXIT_NOTINSTALLED
    fi

    # Let qemu/binfmt_misc do its thing
    mkarchroot_flags+=( -f "$interpreter" -s )
  fi
}

# Usage: chroot-run $copydir $cmd...
chroot-run() {
  local copydir=$1 ; shift ;
  local cmd=( "$@" )
  local mkarchroot_flags=( "${MkarchrootFlags[@]}" )

  hack_mkarchroot_flags "$copydir" # modifies $mkarchroot_flags

  cmd=(
    "$ChrootRun"
    "${mkarchroot_flags[@]}"
    "${ChrootRunFlags[@]}"
    --
    "$copydir"
    "${cmd[@]}"
  )

  "${cmd[@]}"
}

# Usage: mkarchroot $copydir $pkgs...
mkarchroot() {
  local copydir=$1 ; shift ;
  local pkgs=( "$@" )
  local mkarchroot_flags=( "${MkarchrootFlags[@]}" )

  hack_mkarchroot_flags "$copydir" # modifies $mkarchroot_flags

  local cmd=(
    unshare -m "$Mkarchroot"

    # mkarchroot flags:
    "${mkarchroot_flags[@]}"

    --

    # chroot directory:
    "$copydir"

    # pacman flags:
    # * hack around https://bugs.archlinux.org/task/49347
    --hookdir="$copydir/etc/pacman.d/hooks"

    # packages:
    # * and maybe more flags... pacstrap injects flags at the end,
    #   so we can't disable flag parsing with '--')
    "${pkgs[@]}"
  )

  "${cmd[@]}"
}


################################################################################
# Main program                                                                 #
################################################################################

readonly COMMANDS=(
  make sync delete
  install-file install-name upgrade clean-pkgs
  run enter clean-repo help
)

usage() {
  local mount_msg="$(_ 'PATH[:INSIDE_PATH[:OPTIONS]]')"

  print  "Usage: %s [OPTIONS] COMMAND [ARGS...]" "${0##*/}"
  echo
  print  "Create, manage, and maintain libre chroots (similar to \`arch-chroot\`)."
  echo
  prose  "This is configured with \`chroot.conf\`,
          either in \`/etc/libretools.d/\` or \`\$XDG_CONFIG_HOME/libretools/\`.
          The configurable variables are:"
  bullet   '$CHROOTDIR'
  bullet   '$CHROOT'
  bullet   '$CHROOTEXTRAPKG'
  echo
  prose  "Each chroot is named; and there may be multiple chroots;
          all of which are stored under %s by default,
          unless a absolute path is specified with the \`%s\` option.
          If unspecified, the default chroot name is %s, per %s.
          Each work chroot has a pristine, read-only master chroot (\`%s\`),
          which is created automatcally if not present,
          and is used as the seed for any number of named working copies,
          which may be derived from it quickly."
         '$CHROOTDIR' -l '$CHROOT' chroot.conf root
  prose  "Still, creating/deleting/synchronizing a copy is relatively slow;
          but it can be very fast, if %s is on a btrfs partition." '$CHROOTDIR'
  prose  "If the work chroot is not explicitly specified as an absolute path,
          the working copy will be located beside its seed chroot.
          The full path to the seed and copy is of the form: %s, eg:" \
          '$CHROOTDIR/$CHROOT/$COPY'
  echo   '  |$CHROOTDIR       |$CHROOT|$COPY  |'
  echo   "  /var/lib/archbuild/default/root"
  echo   "  /var/lib/archbuild/default/lukeshu"
  prose  "... where %s is %s, which is determined at runtime, per %s.
          %s is normally the local login of the invoking user,
          but may be over-ridden by setting %s in the environment." \
         '$COPY' '$LIBREUSER' /usr/lib/libretools/conf.sh           \
         '$LIBREUSER' '$SUDO_USER'
  echo
  prose  "The current settings for the above variables are:"
  bullet   '%s : %s'      '$LIBREUSER' "${LIBREUSER:-$(_ 'ERROR: NO SETTING')}"
  bullet   '%s : %s'      '$CHROOTDIR' "${CHROOTDIR:-$(_ 'ERROR: NO SETTING')}"
  bullet   '%s    : %s'   '$CHROOT'    "${CHROOT:-$(   _ 'ERROR: NO SETTING')}"
  bullet   '%s      : %s' '$COPY'      "${COPY:-}"
  bullet   '%s   : %s'    '$rootdir'   "${rootdir:-$(  _ 'ERROR'            )}"
  bullet   '%s   : %s'    '$copydir'   "${copydir:-$(  _ 'ERROR'            )}"
  echo
  prose  "If the chroot-set or working copy does not exist, it will be created
          automatically. The chroots in their initial and cleaned states are
          comprised of the packages required by the '%s' and '%s' meta-packages.
          Any packages configured by %s in %s are installed per \`%s\`,
          as if they were %s."                                           \
         base base-devel '$CHROOTEXTRAPKG' /etc/libretools.d/chroot.conf \
         libremakepkg 'PKGBUILD $makedepends'
  prose  "The packages installed into the chroot, will be those found
          in the standard Parabola repos: (%s, %s, %s, %s, %s),
          regardless of the %s configuration of the host system.
          The configuration files in the chroot will also be the standard ones
          installed by the \'%s\' package.
          The \`%s\`, \`%s\`, and \`%s\` options will over-ride the default configs;
          and other tools (such as \`%s\`) are able to over-ride them later." \
         libre core extra community pcr                                       \
         pacman/makepkg pacman                                                \
         -C -M -A libremakepkg
  echo
  prose  "This command will make the following configuration changes in the chroot:"
  bullet   "overwrite %s" /etc/libretools.d/chroot.conf # libretools/librechroot
  bullet   "overwrite %s" /etc/pacman.d/mirrorlist      # devtools/chroot-run
  bullet   "set %s in %s" CacheDir /etc/pacman.conf     # devtools/chroot-run
  prose  "If an over-ride %s is specified with the \`%s\` option,
          the changes above are made after the file is copied in.
          The \`%s\` option will not prevent these modifications." pacman.conf -C -C
  echo
  prose  "The processor architecture of the chroot is determined by the %s
          variable configrured in the %s file, inside of the chroot.
          The \`%s\` option allows specifying an over-ride of the standard file." \
         '$CARCH' /etc/makepkg.conf -M
  echo
  prose  "The \`%s\` option is the preferred way to create new chroot-sets. E.g.:" -A
  echo   "  $ sudo librechroot -A i686 -n my-32bit-x86 make"
  print  "The \`%s\` option sets \`%s\` and \`%s\` implicitly, as:" -A -C -M
  flag   '-C' "%s" "${PACMAN_DEFS_DIR}/pacman.conf.\$<CARCH>"
  flag   '-M' "%s" "${PACMAN_DEFS_DIR}/makepkg.conf.\$<CARCH>"
  prose  "However, %s will be modified to:" pacman.conf
  bullet   "set %s to match %s per %s" Architecture '$CARCH' makepkg.conf
  bullet   "comment-out any '%s' lines" 'Include = /etc/pacman.d/*.conf'
  bullet   "add special-case build support repos (commented-out)"
  prose  "If none of the \`%s\`, \`%s\`, or \`%s\` options are given, the chroot
          architecture will be that of the host." -A -C -M
  echo
  flag 'Options:'                                                                        \
         "-n <$(_ NAME)>"    "Name of the chroot to use"                                 \
         "-l <$(_ COPY)>"    "Name of, or absolute path to, the copy to use"             \
         "-i <$(_ INIT)>"    "Specify the init-system to install, one of:                \
                              [ systemd non-systemd ] (default: systemd)"                \
         "-C <$(_ FILE)>"    "Copy this file to chroot as: %s
                              This option is mutually exclusive with \`%s\`."            \
                             /etc/pacman.conf -A                                         \
         "-M <$(_ FILE)>"    "Copy this file to chroot as: %s
                              This option is mutually exclusive with \`%s\`."            \
                             /etc/makepkg.conf -A                                        \
         "-A <$(_ CARCH)>"   "Specify the architecture of a new '%s' seed.
                              This option is mutually exclusive with %s and %s."         \
                             root -C -M
         '-I'                "Allow packages older than their database entries to remain
                              installed, after updating the database manually.
                              This option can lead to an insane system configuration.
                              Replacement packages will still be applied, for example,
                              unless they are help back explicitly; and there may be
                              dependency conflicts or shared library mismatches.
                              Use this only in extreme circumstances; such as if you
                              need to enable [testing] without synchronizing afterward." \
         "-N"                "Enable networking in the chroot"                           \
         "-w <${mount_msg}>" "Bind mount a file or directory, read/write"                \
         "-r <${mount_msg}>" "Bind mount a file or directory, read-only"
  echo
  flag "Commands (create/copy/delete):"                         \
         'make'   "Create a '%s' seed and working copy"    root \
         'sync'   "Sync the copy with the clean '%s' seed" root \
         'delete' "Delete the working copy"
  flag "Commands (packages):"                                                              \
         "install-file <$(_ FILES)...>" "Like \`%s\`" "pacman -U <$(_ FILES)...>"          \
         "install-name <$(_ NAMES)...>" "Like \`%s\`" "pacman -S <$(_ NAMES)...>"          \
         'upgrade'                      "Like \`%s\`" 'pacman -Syu'                        \
         'clean-pkgs'                   "Remove all packages from the working copy
                                         that are not declared in '%s', '%s', '%s',
                                         or in the %s or %s arrays of the copy's %s,
                                         ensuring that all declared packages are kept.
                                         Note that \`%s\` does this implicitly.
                                         If this fails, the most common reason is an
                                         out-dated %s database. Run the %s command first." \
                                        base base-devel '$CHROOTEXTRAPKG' depends          \
                                        makedepends /startdir/PKGBUILD libremakepkg        \
                                        pacman upgrade
  flag "Commands (maintenance):"                                                       \
         "run <$(_ COMMAND)>" "Run %s in the working copy" "<$(_ COMMAND)>"            \
         'enter'            "Enter an interactive shell in the working copy"           \
         'clean-repo'       "Clean the '%s' repo and %s directory in the working copy" \
                            repo /repo
  flag "Commands (misc):"           \
         'help' "Show this message"
}

# Usage: ExitInvalidArgument error_fmt [ error_arg1 [ error_arg2 [ ... ] ] ]
ExitInvalidArgument()
{
  (( $# )) && error "$@"
  print "See: \`%s help\` for usage" "${0##*/}"

  exit $EXIT_INVALIDARGUMENT
}

# Globals: $CHROOTDIR, $CHROOT, $COPY, $rootdir and $copydir
main() {
  COPY=$( [[ $LIBREUSER == root ]] && echo copy || echo "$LIBREUSER" )
  SANE=true

  declare -i was_conf_error=0
  load_conf chroot.conf CHROOTDIR CHROOT || was_conf_error=$?

  local mode=enter opt
  declare -Ai used_opts

  local target_arch=$(uname -m)
  local use_tmp_pacmanconf=0
  local init=systemd
  local def_pacmanconf="${PACMAN_DEFS_DIR}"/pacman.conf.${target_arch}
  local def_makepkgconf="${PACMAN_DEFS_DIR}"/makepkg.conf.${target_arch}
  local seed_pacmanconf="${def_pacmanconf}"
  local seed_makepkgconf="${def_makepkgconf}"
  local tmp_pacmanconf
  tmp_pacmanconf="$(mktemp --tmpdir librechroot-pacman.conf.XXXXXXXXXX)"

  trap "[[ ! -f \"$tmp_pacmanconf\" ]] || rm -f -- \"$tmp_pacmanconf\"" EXIT


  ## parse CLI options ##

  while getopts 'n:l:i:C:M:A:INw:r:' opt; do
    case $opt in
      n) CHROOT=$OPTARG                                                        ;;
      l) COPY=$OPTARG                                                          ;;
      i) [[ "$OPTARG" != non-systemd ]] || init=non-systemd                    ;;
      C) seed_pacmanconf="$OPTARG"                                             ;;
      M) seed_makepkgconf="$OPTARG"
         target_arch=$(detect_chroot_arch "$OPTARG")                           ;;
      A) target_arch=$OPTARG
         def_pacmanconf="${PACMAN_DEFS_DIR}"/pacman.conf.${target_arch}
         def_makepkgconf="${PACMAN_DEFS_DIR}"/makepkg.conf.${target_arch}
         seed_pacmanconf="${tmp_pacmanconf}" ; use_tmp_pacmanconf=1 ;          ;;
      I) SANE=false                                                            ;;
      N) ChrootRunFlags+=( -N )                                                ;;
      w) ChrootRunFlags+=(-b "-B:$OPTARG")                                     ;;
      r) ChrootRunFlags+=(-b "-Br:$OPTARG")                                    ;;
      *) ExitInvalidArgument                                                   ;;
    esac
    used_opts[$opt]+=1
  done
  MkarchrootFlags+=( -C "${seed_pacmanconf}" -M "${seed_makepkgconf}" )
  mode=${!OPTIND}
  shift $OPTIND


  ## validate and finalize state ##

  if (( was_conf_error )); then
    error "Could not load chroot.conf configuration"
    exit $was_conf_error
  fi

  eval "$(calculate_directories)"
  readonly CHROOTDIR CHROOT COPY SANE
  readonly rootdir copydir
  readonly mode


  ## validate CLI options ##

  for opt in n l C M A; do
    if (( ${used_opts[$opt]:-0} > 1 )); then
      ExitInvalidArgument "$(_ 'Option -%s may only be given once')" "$opt"
    fi
  done
  if (( ${used_opts[A]:-0} && ( ${used_opts[C]:-0} || ${used_opts[M]:-0} ) )); then
    ExitInvalidArgument "$(_ 'Option -A may not be used together with -C or -M')"
  fi
  if [[ -z "${mode}" ]]; then
    ExitInvalidArgument "$(_ 'Must specify a command')"
  fi
  if ! in_array "$mode" "${COMMANDS[@]}"; then
    ExitInvalidArgument "$(_ 'Unrecognized command: %s')" "$mode"
  fi

  case "$mode" in
    help)
      usage
      return $EXIT_SUCCESS
      : ;;
    make|sync|delete|upgrade|enter|clean-pkgs|clean-repo)
      if [[ $# -gt 0 ]]; then
        ExitInvalidArgument "$(_ 'Command `%s` does not take any arguments: %s')" "$mode" "$*"
      fi
      : ;;
    install-file)
      if [[ $# -lt 1 ]]; then
        ExitInvalidArgument "$(_ 'Command `%s` requires at least one file')" "$mode"

      else
        local missing=()
        local file
        for file in "$@"; do
          if ! [[ -f $file ]]; then
            missing+=("$file")
          fi
        done
        if [[ ${#missing[@]} -gt 0 ]]; then
          ExitInvalidArgument "$(_ '%s: file(s) not found: %s')" "$mode" "${missing[*]}"
        fi
      fi
      : ;;
    install-name)
      if [[ $# -lt 1 ]]; then
        ExitInvalidArgument "$(_ 'Command `%s` requires at least one package name')" "$mode"
      fi
      : ;;
    run)
      if [[ $# -lt 1 ]]; then
        ExitInvalidArgument "$(_ 'Command `%s` requires at least one argument')" "$mode"
      fi
      : ;;
    # obsolete commands
    noop)   # `make` has better semantics (it may or may not do some work)
        ExitInvalidArgument "$(_ 'Command `noop` is obsolete. Use `make` instead.')"
      : ;;
    update) # `upgrade` has better semantics
        ExitInvalidArgument "$(_ 'Command `update` is obsolete. Use `upgrade` instead.')"
      : ;;
  esac
  if ! [[ -f "${def_pacmanconf}" && -f "${def_makepkgconf}" ]]; then
    ExitInvalidArgument "$(_ 'Unsupported architecture: %s. See the files in %q for valid architectures.')" \
                        "${target_arch}" "${PACMAN_DEFS_DIR}/"
  fi


  ## process CLI options ##

  if (( use_tmp_pacmanconf )); then
    readonly REPOS_HEADER='###########################\n# Parabola standard repos #'
    readonly VOLATILE_REPOS='\
##############################\
# Special-case build-support #\
##############################\
\
# Enable the volatile arm [arm-aur] repo only as needed\
# [arm-aur]\
# Server = https://mirror.archlinuxarm.org/$arch/$repo/\
\
# Enable the volatile i686 [build-support] repo only as needed\
# [build-support]\
# Server = http://mirror.archlinux32.org/$arch/$repo/\
\
# Enable the volatile i686 [staging] repo only as needed\
# [staging]\
# Server = http://mirror.archlinux32.org/$arch/$repo/\
\
# Enable the volatile x86_64 [staging] repo only as needed\
# [staging]\
# Server = http://mirror.archlinux.org/$arch/$repo/'

    # generate custom pacman.conf
    sed -r                                                           \
        -e "s|^#?\\s*Architecture.+|Architecture = ${target_arch}|g" \
        -e "s|^.*Include\s*=\s*/etc/pacman.d/.*\.conf|#&|"           \
        -e "N ; /${REPOS_HEADER}/ i ${VOLATILE_REPOS}\n\n"           \
        < "${def_pacmanconf}"                                        \
        > "${tmp_pacmanconf}"
  fi


  ## environment validation and chroot instantiation ##

  if (( EUID )); then
    error "The '%s' command must be run with super-user privileges." $mode
    return $EXIT_NOPERMISSION
  fi

  umask 0022

  # Keep this lock for as long as we are running
  # Note that '9' is the same FD number as in mkarchroot et al.
  lock 9 "$copydir.lock" \
    "Waiting for existing lock on working copy to be released: [%s]" "$COPY"

  if [[ $mode != delete ]]; then
    if ! check_mountpoint "$copydir.lock"; then
      error "Chroot copy is mounted with 'nosuid' or noexec options: [%s]" "$COPY"
      return $EXIT_FAILURE
    fi

    # Create chroot seed
    local chroot_pkgs=( $(base_pkgs $init) )
    if [[ ! -d $rootdir ]]; then
      if (( ${#chroot_pkgs[*]} )); then
        msg "Creating 'root' seed for chroot [%s]" "$CHROOT"
        mkarchroot "$rootdir" ${chroot_pkgs[*]} < /dev/null
        make_empty_repo "$rootdir"
      else
        error "No %s defined. Is \`%s\` corrupted?" '$BASE_PKGS' '$(librelib conf)'
        return $EXIT_MISCONFIGURED
      fi
    fi

    # Create or sync working copy
    if [[ ! -d $copydir ]] || [[ $mode == sync ]]; then
      msg "Syncing copy [%s] with root copy" "$COPY"
      sync_chroot "$CHROOTDIR/$CHROOT/root" "$copydir" "$COPY"
    fi


    ## chroot configuration ##

    # The $fresh_pkgs optimization in chcleanup.sh assumes that none of
    # CHROOTPKG, CHROOTEXTRAPKG, or their dependencies are virtual packages.
    # Also, `chcleanup` would fail if any of these are unavailable; but is slow.
    # We can abort much sooner by validating these before processing.
    local multiple_fmt="$(_ "Package '%s' configured in %s has multiple providers.")"
    local explicit_fmt="$(_ "Be explicit (eg: %s).")"
    local virtual_fmt="$( _ "Package '%s' configured in %s is unavailable or is virtual.")"
    local no_pkg_fmt="$(  _ "Package '%s' configured in %s is unavailable.")"
    local pkg_set pkg n_providers
    for pkg_set in chroot_pkgs CHROOTEXTRAPKG; do
      declare -n pkgset=$pkg_set
      for pkg in ${pkgset[*]}; do
        ! [[ "$pkg" =~ ^(base|base-devel)$ ]] || continue

        n_providers=$(( $(pacsift --sync --any --exact --satisfies=$pkg | wc -l) ))
        if   (( n_providers  > 1 )); then
          printf "$multiple_fmt $explicit_fmt\n" $pkg "\$$pkg_set" '<repo>/<pkgname>'
        elif (( n_providers != 1 )) && ! [[ "$pkg" =~ / ]]; then
          printf "$virtual_fmt $explicit_fmt\n" $pkg "\$$pkg_set" '<repo>/<pkgname>'
        elif (( n_providers != 1 )) && ! LANG=C pacman -Si $pkg &> /dev/null; then
          printf "$no_pkg_fmt\n" $pkg "\$$pkg_set" # `pacsift` does not handle '/'
        fi
      done
    done

    echo "CHROOTEXTRAPKG=( $(printf '%q ' "${CHROOTEXTRAPKG[@]}") )" |
    install -Dm644 /dev/stdin          "$copydir"$CHROOT_CONF
    install -Dm644 $LIBRETOOLS_CONF_SH "$copydir"$LIBRETOOLS_CONF_SH

    # "touch" the chroot first
    # this will
    #  - overwrite '/etc/pacman.d/mirrorlist'"
    #  - set 'CacheDir' in \`/etc/pacman.conf'"
    #  - apply -C or -M flags
    chroot-run "$copydir" true < /dev/null
  fi

  # cleanup
  [[ ! -f "$tmp_pacmanconf" ]] || rm -f -- "$tmp_pacmanconf"
  trap EXIT          # clear the trap to remove the temporary pacman.conf
  MkarchrootFlags=() # XXX dirty hack, don't apply -C or -M again


  ## handle commands ##

  case "$mode" in
    # Create/copy/delete
    make|sync) : ;; # make and sync operations are managed implicitly above
    delete)
      if [[ -d $copydir ]]; then
        delete_chroot "$copydir"
      fi
      ;;

    # Dealing with packages
    install-file)
      install_packages         "$copydir" "$@" < /dev/null
      chroot_add_to_local_repo "$copydir" "$@"
      ;;
    install-name)
      chroot-run "$copydir" pacman -Sy --noconfirm -- "$@" < /dev/null
      ;;
    upgrade)
      chroot-run "$copydir" pacman -Syu --noconfirm < /dev/null
      ;;
    clean-pkgs)
      trap "rm -f -- ${copydir@Q}{$CHCLEANUP_FILE,$CHROOTEXEC_FILE}" EXIT
      install -m755 "$(librelib chroot/chcleanup)" "$copydir"$CHCLEANUP_FILE
      printf '%s\n' '#!/bin/bash' ''        \
                    'mkdir -p /startdir'    \
                    'cd /startdir'          \
                    "SANE=$SANE /chcleanup" > "$copydir"$CHROOTEXEC_FILE
      chmod 755  "$copydir"$CHROOTEXEC_FILE
      chroot-run "$copydir"$CHROOTEXEC_FILE < /dev/null
      ;;

    # Other
    run)
      chroot-run "$copydir" "$@"
      ;;
    enter)
      chroot-run "$copydir" bash
      ;;
    clean-repo)
      rm -rf "${copydir}"/repo/*
      make_empty_repo "$copydir"
      ;;
  esac
}


main "$@"