ubuntu ctd
[build.git] / build.common
1 # -*-Shell-script-*-
2 #
3 # Common functions for build scripts used by various packages
4 # incorporated (e.g., build, bootcd, nodeimage, sliceimage)
5 #
6 # Marc E. Fiuczynski <mef@cs.princeton.edu>
7 # Copyright (C) 2007 The Trustees of Princeton University
8 # Thierry Parmentelat <thierry.parmentelat@inria.fr> INRIA
9 #
10 # supported distros f8, f10, f12, f14, f16, centos5, sl6
11 #
12 # for locating pkgs.py
13 export PATH=.:$PATH
14
15 # returns 'Fedora' or 'CentOS' for now
16 function pl_getDistro() {
17     if [ -f "/etc/redhat-release" ] ; then
18         distro=$(awk ' { print $1 } ' /etc/redhat-release)
19         case $distro in Scientific*) distro="SL" ; esac
20     elif [ -f /etc/lsb-release ] ; then
21         . /etc/lsb-release
22         echo $DISTRIB_CODENAME 
23     elif [ -f /etc/debian_version ] ; then
24         case $(cat /etc/debian_version) in
25             6.0.6) distro=squeeze ;;
26             7.0)   distro=wheezy  ;;
27             *)     distro=unknown.debian.in.build.common ;;
28         esac
29     fi
30     [ -z "$distro" ] && { echo "build.common.pl_getDistro-unknown"; exit 1; }
31     echo "$distro"
32     return 0
33 }
34
35 # returns something like 8, 10, or 5.3
36 function pl_getRelease() {
37     if [ -f "/etc/redhat-release" ] ; then
38         release=$(awk ' { if ($1=="Fedora" && $2=="Core") print $4 ; if (($1=="Fedora" && $2!="Core")||$1=="CentOS") print $3 ; if ($1=="Scientific") print $4 } ' /etc/redhat-release)
39     else
40         echo "build.common.pl_getRelease-unknown"
41         exit 1
42     fi
43     # keep only the major number
44     echo "$release" | cut -d. -f1
45     return 0
46 }
47
48 # returns distro shortname, something like 'f8' or 'centos5'
49 function pl_getReleaseName () {
50     distro=$1; shift
51     release=$1; shift
52     case $distro in
53         [Ff]edora*)
54             releasename=f$release
55             ;;
56         [Cc]entOS*)
57             old_IFS="$IFS"
58             IFS="."
59             set -- $release
60             IFS="$old_IFS"
61             releasename=centos$1
62             ;;
63         [Ss]L*)
64             releasename=sl$release
65             ;;
66         squeeze|wheezy|oneiric|precise|quantal)
67             releasename=$distro
68             ;;
69         *)
70             releasename="unknown-name-for-${pl_DISTRO}-please-edit-build.common"
71             echo 1>&2 "build.common: WARNING - releasename not set for distro=$distro" 
72             return 1
73             ;;
74     esac
75     echo "$releasename"
76     return 0
77 }
78
79 # yum exclusions are now defined in yumexclude.pkgs
80 # so they can now depend both on the linux distro and the pl distro
81 function pl_yumexclude () {
82     keyword=$1; shift
83     fcdistro=$1; shift
84     pldistro=$1; shift
85     builddir=$1; shift
86     # search for file "yumexclude.pkgs"
87     yumexclude_file=$(pl_locateDistroFile $builddir $pldistro "yumexclude.pkgs")
88     #
89     # check if pkgs.py is in PATH
90     type -p pkgs.py >& /dev/null || export PATH=$builddir:$PATH
91
92     # parse it
93     pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro $keyword $yumexclude_file || \
94         { echo pl_yumexclude failed with fcdistro=$fcdistro and pldistro=$pldistro; return 1 ; }
95 }
96
97 # <> fcdistro pldistro builddir
98 # node side : use the 'nodeyumexclude' keywork in yumexclude.pkgs
99 function pl_nodeyumexclude () { pl_yumexclude 'nodeyumexclude' "$@" ; }
100 # server side : use the 'plcyumexclude' keywork in yumexclude.pkgs
101 function pl_plcyumexclude () { pl_yumexclude 'plcyumexclude' "$@" ; }
102
103
104 # figure out which redhat distro we are using (fedora, centos, redhat)
105 pl_DISTRO=$(pl_getDistro)
106
107 # select basearch of the host devel environment - protected for macos for local tests
108 # try arch for testing stuff on a mac
109 pl_DISTRO_ARCH=$(uname -i 2>/dev/null || arch 2> /dev/null || echo unknownarch)
110
111 # the release number (plain number)
112 pl_DISTRO_RELEASE=$(pl_getRelease)
113
114 # the release name - something like 'f8' or 'sl6'
115 pl_DISTRO_NAME=$(pl_getReleaseName $pl_DISTRO $pl_DISTRO_RELEASE)
116
117 # get path to appropriate yumgroups.xml file
118 # Thierry: quick & dirty improvement 
119 # this file is updated by the toplevel build, from the .pkgs files
120 pl_DISTRO_YUMGROUPS="../../../RPMS/yumgroups.xml"
121
122 function pl_process_fedora_options () {
123     # Get options
124     shiftcount=0
125     while getopts "l:r:a:h" opt ; do
126         case $opt in
127             l)
128                 pl_DISTRO_URL=$OPTARG
129                 let shiftcount=$shiftcount+2
130                 ;;
131             r)
132                 pl_DISTRO_RELEASE=$OPTARG
133                 let shiftcount=$shiftcount+2
134                 ;;
135             a)
136                 pl_DISTRO_ARCH=$OPTARG
137                 let shiftcount=$shiftcount+2
138                 ;;
139             h|*)
140                 echo "Usage: $0 [OPTION]..."
141                 echo "  -l url          distro mirror location (default: $pl_DISTRO_URL)"
142                 echo "  -r release      distro release number (default: $pl_DISTRO_RELEASE)"
143                 echo "  -a arch         distro architecture (default: $pl_DISTRO_ARCH)"
144                 echo "where distro can be either fedora, centos, or redhat"
145                 echo "  -h              This message"
146                 exit 1
147                 ;;
148         esac
149     done
150     return $shiftcount
151 }
152
153 ######################################## handling a root image
154 function pl_root_rpm_macros () {
155     cat <<EOF
156 %_install_langs C:en_US:en
157 %_netsharedpath /proc:/dev/pts:/usr/share/info
158 %_excludedocs 1
159 %__file_context_path /dev/null
160 EOF
161 }
162
163 function pl_root_makedevs() {
164     vroot=$1
165     # Clean ${vroot}/dev, but only when ${vroot}!=""
166     [ -n $vroot ] && rm -rf $vroot/dev
167     
168     mkdir -p $vroot/dev
169     mknod -m 666 $vroot/dev/null c 1 3
170     mknod -m 666 $vroot/dev/zero c 1 5
171     mknod -m 666 $vroot/dev/full c 1 7
172     mknod -m 644 $vroot/dev/random c 1 8
173     mknod -m 644 $vroot/dev/urandom c 1 9
174     mknod -m 666 $vroot/dev/tty c 5 0
175     mknod -m 666 $vroot/dev/ptmx c 5 2
176     # For bash command substitution
177     ln -nsf ../proc/self/fd $vroot/dev/fd
178
179     # For df and linuxconf
180     touch $vroot/dev/hdv1
181
182     # For pseudo ttys
183     mkdir -p $vroot/dev/pts
184
185     # for tmpfs mount
186     mkdir -p $vroot/dev/shm
187
188     # For TUN/TAP
189     mkdir -p $vroot/dev/net
190     mknod -m 600 $vroot/dev/net/tun c 10 200
191
192     # For mkinitrd (in case a kernel is being installed)
193     # As well as for loop back mounting within a vm. 
194     for i in $(seq 0 255) ; do
195         mknod -m 640 $vroot/dev/loop$i b 7 $i
196     done
197 }
198
199 function mkfedora_usage() {
200     echo "Usage: pl_root_mkfedora [OPTION]... basedir pldistro pkgsfile(s)"
201     echo "      -l url          Fedora mirror location."
202     echo "                      Defaults are searched in <pldistro>.mirrors"
203     echo "      -v              Be verbose"
204     echo "      -h              This message"
205     echo " target selection (defaults based on current build VM context)"
206     echo "      -r release      Fedora release number (default: $releasever)"
207     echo "      -a arch         Fedora architecture (default: $basearch)"
208     exit 1
209 }
210
211 function pl_root_mkfedora () {
212
213     echo "* Entering pl_root_mkfedora" "$@"
214
215     if [ $UID -ne 0 ] ; then
216         echo "Error: You must run this script as root."
217         exit 1
218     fi
219
220 # Verbosity
221     verbose=0
222
223 # Release and architecture to install : defaults to current vm settings or previously parsed fedora_options
224     releasever=$pl_DISTRO_RELEASE
225     basearch=$pl_DISTRO_ARCH
226
227 # Get options
228     while getopts "vh" opt ; do
229         case $opt in
230             v) verbose=1; set -x ;;
231             h|*) mkfedora_usage ;;
232         esac
233     done
234
235     shift $(($OPTIND - 1))
236     [[ "$#" -lt 3 ]] && mkfedora_usage
237     vroot=$1 ; shift
238     pldistro=$1 ; shift
239     pkgsfile="$@"
240     vroot=$(cd $vroot && pwd -P)
241     [ -d $vroot ] || mkfedora_usage
242
243
244     # parse pkgsfile and add to local vars
245     fcdistro=${pl_DISTRO_NAME}
246     pkgs_packages=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro package $pkgsfile) 
247     pkgs_groups=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro group $pkgsfile)
248     # what can get trashed to save space
249     pkgs_junk=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro junk $pkgsfile)
250     # but not this
251     pkgs_precious=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro precious $pkgsfile)
252     # formerly related to mkfedora -k : packages to take from our own build 
253     # and thus need be excluded frem the stock repos
254     # locate builddir by looking for pkgs.py
255     builddir=$(dirname $(type -p pkgs.py))
256     SUBST_NODEYUMEXCLUDE=$(pl_nodeyumexclude $fcdistro $pldistro $builddir)
257     pkgs_yumexclude=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro yumexclude $pkgsfile | sed -e s,@NODEYUMEXCLUDE@,"$SUBST_NODEYUMEXCLUDE",)
258     # get mirrors if not specified with -l
259     if [ -z "$mirrors" ] ; then
260         mirrorsfile=$(pl_locateDistroFile ../build/ $pldistro "$pldistro.mirrors")
261         # do not sort mirrors, keep order from input
262         mirrors=$(pkgs.py -u -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro mirror $mirrorsfile)
263     fi
264
265     yumexclude_line=""
266     [ -n "$pkgs_yumexclude" ] && yumexclude_line="exclude=$pkgs_yumexclude"
267
268     echo "$0: candidate mirrors"
269     for mirror in $mirrors ; do
270         echo "* candidate mirror $mirror"
271     done
272
273     # the repo part of the final yum.conf
274     yum_conf_repos=$vroot/xxxmkfedora-repos.confxxx
275     if ! yumconf_mirrors $yum_conf_repos ../build/ $fcdistro "$yumexclude_line" $mirrors ; then
276         echo xxx -- error ; return 1
277     fi
278     
279     # Do not tolerate errors
280     set -e
281
282     public_gpg_key=$(yumconf_gpgkey $yum_conf_repos)
283
284     ## make rpms ignore installing stuff to special fs entries like /proc
285     # Because of https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=52725
286     # you have to use at least one language beside 'C'
287     # Prevent all locales from being installed in reference image
288     mkdir -p $vroot/etc/rpm
289     pl_root_rpm_macros > $vroot/etc/rpm/macros 
290
291     # Trick rpm and yum, who read the real root /etc/rpm/macros file
292     # rather than the one installed in the reference image, despite what
293     # you might expect the --root and --installroot options to mean. Both
294     # programs always read $HOME/.rpmmacros.
295     export HOME=$vroot/tmp
296     mkdir -p $vroot/tmp
297     pl_root_rpm_macros > $vroot/tmp/.rpmmacros
298
299     function mkfedora_cleanup () {
300         umount -l $vroot/proc
301         umount -l $vroot/dev/shm
302         umount -l $vroot/dev/pts
303     }
304
305     # Clean up before exiting if anything goes wrong
306     trap "mkfedora_cleanup" ERR INT
307
308     # Mount in reference image
309     mount -t devpts none $vroot/dev/pts
310     mount -t tmpfs none $vroot/dev/shm
311     mkdir -p $vroot/proc
312     mount -t proc none $vroot/proc
313     
314     # Create a /var/lib dirs for yum & rpm
315     mkdir -p $vroot/var/lib/yum
316     mkdir -p $vroot/var/lib/rpm
317     mkdir -p $vroot/usr/share/info
318
319     # Create a dummy /etc/fstab in reference image
320     mkdir -p $vroot/etc
321     cat >$vroot/etc/fstab <<EOF
322 # This fake fstab exists only to please df and linuxconf.
323 /dev/hdv1       /       ext2    defaults        1 1
324 EOF
325     cp $vroot/etc/fstab $vroot/etc/mtab
326
327     # Necessary for some scripts
328     mkdir -p $vroot/etc/sysconfig
329     echo "NETWORKING=yes" > $vroot/etc/sysconfig/network
330
331     # Initialize RPM database in reference image
332     mkdir -p $vroot/var/lib/rpm
333     rpm --root $vroot --initdb
334     rpm --root $vroot --import $public_gpg_key
335
336     # Initialize yum in reference image
337     mkdir -p $vroot/var/cache/yum $vroot/var/log
338
339 # yum.conf is for building only - store in different location than /etc/yum.conf
340     yum_conf=$vroot/etc/mkfedora-yum.conf
341     cat > $yum_conf <<EOF
342 [main]
343 cachedir=/var/cache/yum
344 debuglevel=2
345 logfile=/var/log/yum.log
346 pkgpolicy=newest
347 multilib_policy=best
348 distroverpkg=redhat-release
349 tolerant=1
350 exactarch=1
351 retries=20
352 obsoletes=1
353 gpgcheck=0
354 # Prevent yum-2.4 from loading additional repository definitions
355 # (e.g., from /etc/yum.repos.d/)
356 reposdir=/dev/null
357 EOF
358     
359     cat $yum_conf_repos >> $yum_conf
360
361     # If we are being built as part of an automated RPM build, solve the
362     # bootstrap problem by including any just built packages in the yum
363     # configuration. This cooperates with the PlanetLab build system.
364     if [ -n "$RPM_BUILD_DIR" ] ; then
365         RPM_RPMS_DIR=$(cd $(dirname $RPM_BUILD_DIR)/RPMS && pwd -P)
366         # If run under sudo, allow user to delete the headers/ and
367         # repodata/ directories.
368         if [ -n "$SUDO_USER" ] ; then
369             chown -R $SUDO_USER $RPM_RPMS_DIR
370         fi
371         cat >> $yum_conf <<EOF
372
373 [building]
374 name=Building - $basearch - $RPM_RPMS_DIR/
375 baseurl=file://$RPM_RPMS_DIR/
376 EOF
377 fi
378
379     echo "========== Dumping $yum_conf"
380     cat $yum_conf
381     echo "========== EndDump $yum_conf"
382
383     yum_options=""
384 #    yum --help | grep verbose &> /dev/null && yum_options="$yum_options --verbose"
385     yum_options="$yum_options -y"
386     yum_options="$yum_options -c $yum_conf"
387     yum_options="$yum_options --installroot=$vroot"
388
389     # glibc must be specified explicitly for the correct arch to be
390     # chosen.
391     echo "* Installing glibc"
392     # ignore yum's return code that is basically undefined
393     yum $yum_options install glibc || :
394
395     # Go, baby, go
396     if [ -n "$pkgs_packages" ] ; then
397         echo "* Installing optional packages" $pkgs_packages
398         # ignore yum's return code that is basically undefined
399         echo "* Install options" $vroot $yum_options 
400         yum $yum_options install $pkgs_packages || :
401         if ! rpm --root $vroot -q $pkgs_packages >/dev/null ; then
402             echo "* Warning: Missing packages"
403             rpm --root $vroot -q $pkgs_packages | grep "not installed"
404         fi
405     fi
406
407     if [ -n "$pkgs_groups" ] ; then
408        ## call yum sequentially to get finer-grained info on dependencies
409         for group_plus in $pkgs_groups ; do
410             group=$(echo $group_plus | sed -e "s,+++, ,g")
411             echo "* Installing optional group $group" 
412             # ignore yum's return code that is basically undefined
413             yum $yum_options groupinstall "$group" || :
414         done
415     fi
416
417     # formerly in bootcd/prep.sh : to optimize footprint
418     if [ -n "$pkgs_junk" ] ; then
419         echo "* Removing unnecessary junk"
420         pushd $vroot
421         # Save precious files
422         [ -n "$pkgs_precious" ] && tar --ignore-failed-read -cpf precious.tar $pkgs_precious
423         # Remove unnecessary junk
424         [ -n "$pkgs_junk" ] && rm -rf $pkgs_junk
425         # Restore precious files
426         [ -n "$pkgs_precious" ] && tar -xpf precious.tar && rm -f precious.tar
427         popd
428     fi
429
430     # Clean yum cache
431     echo "* Cleaning up"
432
433     # NOTE: this hack is for Fedora >= 12.
434     # if kernel-debug is installed, clean it up
435     # we link to our version of kernel/initrd and clean up
436     # kernel-debug manually
437     if rpm --root $vroot --quiet -q kernel-debug ; then
438         echo "* Cleaning up kernel-debug - (workaround for f12)"
439         pushd $vroot/boot/
440         rm -rf kernel-boot kernel-bootsmp initrd-boot initrd-bootsmp
441         ln -s vmlinuz-*${pldistro}* kernel-boot
442         ln -s vmlinuz-*${pldistro}* kernel-bootsmp
443         ln -s initrd-*${pldistro}* initrd-boot
444         ln -s initrd-*${pldistro}* initrd-bootsmp
445         rpm --root $vroot --nodeps -e kernel-debug || :
446         popd
447     fi
448
449     # ignore yum's return code that is basically undefined
450     yum $yum_options clean all || :
451
452     # Clean RPM state
453     rm -f $vroot/var/lib/rpm/__db*
454
455     # Set time zone to UTC
456     if [ -f $vroot/usr/share/zoneinfo/UTC -a -f $vroot/etc/localtime ] ; then
457         rm -f $vroot/etc/localtime
458         ln -s /usr/share/zoneinfo/UTC $vroot/etc/localtime
459     fi
460
461     echo "Dumping current list of rpms in /etc/mkfedora-rpms.txt"
462     chroot $vroot rpm -aq | sort > $vroot/etc/mkfedora-rpms.txt
463
464     # remove trap handler, as we are about to call it directly.
465     trap - ERR INT
466
467     # Clean up
468     mkfedora_cleanup
469
470     return 0
471 }
472
473 function pl_root_tune_image () {
474     root=$1; shift
475
476     # Disable all services in reference image
477     chroot $root sh -c "/sbin/chkconfig --list | awk '{ print \$1 }' | xargs -i /sbin/chkconfig {} off"
478
479     # FC2 minilogd starts up during shutdown and makes unmounting
480     # impossible. Just get rid of it.
481     rm -f $root/sbin/minilogd
482     ln -nsf /bin/true $root/sbin/minilogd
483
484     # This tells the Boot Manager that it is okay to update
485     # /etc/resolv.conf and /etc/hosts whenever the network configuration
486     # changes. Users are free to delete this file.
487     touch $root/etc/AUTO_UPDATE_NET_FILES
488 }
489
490 # Move specified directories out of a src tree into a dst tree, and
491 # then for each moved directory create a symlink in src to dst.
492 function pl_move_dirs() {
493     root=$1
494     data=$2
495     store=$3
496     shift 3
497
498     mkdir -p $root/data
499     for datadir in "$@" ; do
500         mkdir -p ${data}${datadir}
501         if [ -d ${root}/${datadir} -a ! -h ${root}/${datadir} ] ; then
502             (cd ${root} && find ./${datadir} | cpio -p -d -u ../${data}/)
503         fi
504         rm -rf ${root}/${datadir}
505         mkdir -p $(dirname ${root}/${datadir})
506         ln -nsf ${store}/${datadir} ${root}/${datadir}
507     done
508 }
509
510 # Construct an image file from given some directory
511 # XXX in the future maybe use livecdtools?
512 function pl_make_image() {
513     root=$1
514     image=$2
515     extraspace=$3
516
517     # Leave about 100 MB free space and allow for about 20% inode overhead
518     bytes=$((($(du -sb $root | cut -f1) + $extraspace) * 120 / 100))
519     bs=4096
520     blocks=$(($bytes / $bs))
521     dd bs=$bs count=$blocks if=/dev/zero of=$image
522     mkfs.ext3 -b $bs -j -F $image
523
524     # Temporarily mount it
525     tmp=$(mktemp -d tmp.XXXXXX)
526     mount -o loop $image $tmp
527     trap "umount $tmp; rmdir $tmp" ERR INT
528
529     # Move files to it
530     (cd $root && tar cpf - .) | (cd $tmp && tar xpf -)
531
532     # Unmount it
533     umount $tmp
534     rmdir $tmp
535     trap - ERR INT
536 }
537
538 # Fix permissions on tmp directories
539 function pl_fixtmp_permissions() {
540     root=$1
541     chmod 1777 $root/tmp $root/usr/tmp $root/var/tmp
542 }
543
544 function pl_fixdirs() {
545     root=$1
546     datadirs=$2
547     for datadir in datadirs ; do
548         if [ -h ${root}/${datadir} ] ; then
549             rm -f ${root}/${datadir}
550             mkdir -p ${root}/${datadir}
551         fi
552     done
553 }
554
555 ########## .pkgs format
556 # Usage: pl_parsePkgs keyword [-a arch] fcdistro pldistro pkgs-file[..s]
557 # pkgs.py should be found in PATH, like this file build.common
558 # only usage should be for pl_getPackages and pl_getGroups,
559 # which in turn are usednow be in {node,slice}image/build.sh
560 function pl_parsePkgs () {
561     target_arch=$pl_DISTRO_ARCH
562     keyword=$1;shift
563     [ "$1" == "-a" ] && { shift; target_arch="$1"; shift; }
564     fcdistro=$1; shift
565     pldistro=$1; shift
566
567     echo 1>&2 "pl_parsePkgs: using -a $target_arch -f $fcdistro -d $pldistro $keyword $@"
568     pkgs.py -a $target_arch -f $fcdistro -d $pldistro $keyword "$@" 
569 }
570 # usage: pl_getPackages [-a arch] fcdistro pldistro pkg-file[..s]
571 function pl_getPackages() { pl_parsePkgs package "$@" ; }
572 function pl_getGroups() { pl_parsePkgs group "$@" ; }
573
574 ##############################
575
576 # locates a pldistro-dependant file
577 # tries first in build/<pldistro>/, then in build/planetlab/
578 function pl_locateDistroFile () {
579     builddir=$1; shift
580     pldistro=$1; shift
581     pkgsfile=$1; shift
582
583     pkgspath=""
584     # if config dir is missing but a .svnpath or a .gitpath exists, use it to extract the config dir
585     configdir="$builddir/config.${pldistro}"
586     if [ ! -d $configdir ] ; then
587         if [ -f "${configdir}.svnpath" -o -f "${configdir}.gitpath" ] ; then
588             echo 1>&2 "Invoking make to extract remote config.${pldistro}"
589             # we set PLDISTROTAGS here to /dev/null because when dealing with remote distros
590             # at a very early stage (like searching for devel.pkgs even before the build VM is created)
591             # then make screams because it cannot find a mandatory include file
592             # OTOH this mechanism here is not intended to depend on tags specifically
593             make 1>&2 --no-print-directory -C $builddir stage1=true config.${pldistro} PLDISTROTAGS=/dev/null
594         fi
595     fi
596     # locate it
597     paths="$builddir/config.$pldistro/$pkgsfile $builddir/config.planetlab/$pkgsfile"
598     for path in $paths; do
599         if [ -f $path ] ; then
600             pkgspath=$path
601             break
602         fi
603     done
604     if [ -z "$pkgspath" ] ; then
605         echo 1>&2 "pl_locateDistroFile - in $(pwd) : cannot locate $pkgsfile in $builddir"
606         echo 1>&2 "candidates were $paths"
607         echo "not-found-by-pl_locateDistroFile"
608         return 1
609     else
610         echo 1>&2 "pl_locateDistroFile: using $pkgspath"
611         echo $pkgspath
612         return 0
613     fi
614 }
615
616 function yumgroups_from_pkgs () {
617     builddir=$1; shift
618     pldistro=$1; shift
619     fcdistro=$1; shift
620     pkgsnames=$@
621
622     sedargs="-e s,@FCDISTRO@,$fcdistro,g"
623
624    cat <<__header
625 <?xml version="1.0"?>
626 <!DOCTYPE comps PUBLIC "-//Red Hat, Inc.//DTD Comps info//EN" "comps.dtd">
627 <comps>
628 __header
629
630     for pkgsname in $pkgsnames; do
631         pkgsfile=$(pl_locateDistroFile $builddir $pldistro $pkgsname)
632         packages=$(pl_getPackages $fcdistro $pldistro $pkgsfile)
633
634         groupname=$(pkgs.py groupname $pkgsfile | sed $sedargs)
635         groupdesc=$(pkgs.py groupdesc $pkgsfile | sed $sedargs)
636
637         if [ -z "$groupname" -o -z "$groupdesc" ] ; then
638             echo "Cannot find groupname: and groupdesc: in $pkgsfile -- skipped" 1>&2
639             continue
640         fi
641         
642         cat << __group_header
643   <group>
644     <id>$(echo $groupname|tr A-Z a-z)</id>
645     <name>$groupname</name>
646     <description>$groupdesc</description>
647     <uservisible>true</uservisible>
648     <packagelist>
649 __group_header
650         for package in $packages; do 
651             echo "<packagereq type=\"mandatory\">$package</packagereq>"
652         done
653         cat << __group_footer
654     </packagelist>
655   </group>
656 __group_footer
657     done
658 cat <<__footer
659 </comps>
660 __footer
661 }
662
663
664 function build_fetch () {
665     curl --fail --silent --max-time 60 --output /dev/null "$1" 
666 }
667
668 # tries to compute a valid yum.conf for that pldistro from the template in mirroring/
669 # returns 0 and writes <dest_yumconf> on success
670 # returns 1 on failure, in which case <dest_yumconf> is deleted
671 function yumconf_mirrors () {
672     dest_yumconf=$1; shift
673     builddir=$1; shift
674     fcdistro=$1; shift
675     yumexclude_line="$1" ; shift
676     mirrors="$@"
677
678     template=$builddir/mirroring/$fcdistro/yum.repos.d/building.repo.in
679     
680     if [ ! -f $template ] ; then
681         echo "yumconf_mirrors: cannot locate template $template"
682         rm -f $dest_yumconf
683         return 1
684     fi
685
686     for mirror in $mirrors; do
687         if yumconf_mirror $dest_yumconf $template "$yumexclude_line" $mirror; then
688             return 0
689         fi
690     done
691     echo 'yumconf_mirrors in build.common : ran out of mirrors -- BAILING OUT'
692     rm -f $dest_yumconf
693     return 1
694 }
695
696 # computes a yum.conf from the template, and checks that all baseurl defined in there are valid repos
697 # returns 0 on success and 1 on failure
698 function yumconf_mirror () {
699     dest_yumconf=$1; shift
700     template=$1; shift
701     yumexclude_line="$1" ; shift
702     mirror=$1; shift
703
704     sed -e "s,@MIRRORURL@,$mirror,g" \
705         -e "/baseurl=/i\\
706 $yumexclude_line" $template > $dest_yumconf
707     
708     # capture all lines defining baseurl
709     baseurl_defs=$(grep '^baseurl=' $dest_yumconf)
710     if [ -z "$baseurl_defs" ] ; then
711         return 1
712     fi
713
714     for baseurl_def in $baseurl_defs; do
715         baseurl=$(echo $baseurl_def | sed \
716             -e s,baseurl=,, \
717             -e 's,$basearch,'"$pl_DISTRO_ARCH",g)
718         repomd=$baseurl/repodata/repomd.xml
719
720         echo "* Trying to fetch $repomd"
721         if ! build_fetch $repomd ; then
722             echo "* Failed to fetch $repomd"
723             return 1
724         fi
725     done
726     echo "* Selected mirror $mirror"
727     return 0
728 }
729
730 # from a yum.conf as generated above, computes the gpgkey urls
731 function yumconf_gpgkey () {
732     dest_yumconf=$1; shift
733
734     values=$(grep -h '^gpgkey=' $dest_yumconf | sed -e s,gpgkey=,, | sed -e 's,$basearch,'"$pl_DISTRO_ARCH",g | sed -e 's, ,\n,g' | sort | uniq | xargs)
735     [ -n "$values" ] || return 1
736     echo $values
737     return 0
738 }
739
740 # patches a yum conf to insert an exclude line in each declared repo
741 function yumconf_exclude () {
742     repo=$1; shift
743     yumexclude_line="$1" ; shift
744     
745     sed -i -e "/#baseurl=.*$/i\\
746 $yumexclude_line" $repo
747 }