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