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