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