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