cb3c208c1c39834e77126c5889ec70c1a0ef5d20
[build.git] / vbuild-init-lxc.sh
1 #!/bin/bash
2 # -*-shell-*-
3
4 #shopt -s huponexit
5
6 COMMAND=$(basename $0)
7 DIRNAME=$(dirname $0)
8 BUILD_DIR=$(pwd)
9
10 # pkgs parsing utilities
11 PATH=$(dirname $0):$PATH export PATH
12 . build.common
13
14 DEFAULT_FCDISTRO=f16
15 DEFAULT_PLDISTRO=planetlab
16 DEFAULT_PERSONALITY=linux64
17 DEFAULT_IFNAME=eth0
18
19 COMMAND_VBUILD="vbuild-init-lxc.sh"
20 COMMAND_MYPLC="vtest-init-lxc.sh"
21
22 lxc_version="0.8.0-rc2"
23 lxc_git_repo="git://lxc.git.sourceforge.net/gitroot/lxc/lxc"
24
25 function bridge_init () {
26
27     # turn on verbosity
28     set -x
29
30     # constant
31     INTERFACE_BRIDGE=br0
32
33     # Default Value for INTERFACE_LAN
34     INTERFACE_LAN=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
35
36
37     echo "========== $COMMAND: entering start - beg"
38     hostname
39     uname -a
40     ifconfig
41     netstat -rn
42     echo "========== $COMMAND: entering start - end"
43
44     # disable netfilter calls for bridge interface (they cause panick on 2.6.35 anyway)
45     #
46     # another option would be to accept the all forward packages for
47     # bridged interface like: -A FORWARD -m physdev --physdev-is-bridged -j ACCEPT
48     sysctl net.bridge.bridge-nf-call-iptables=0
49     sysctl net.bridge.bridge-nf-call-ip6tables=0
50     sysctl net.bridge.bridge-nf-call-arptables=0
51
52     # take extra arg for ifname, if provided
53     [ -n "$1" ] && { INTERFACE_LAN=$1; shift ; }
54
55     #if we have already configured the same host_box no need to do it again
56     /sbin/ifconfig $INTERFACE_BRIDGE &> /dev/null && {
57         echo "Bridge interface $INTERFACE_BRIDGE already set up - $COMMAND start exiting"
58         return 0
59     }
60     /sbin/ifconfig $INTERFACE_LAN &>/dev/null || {
61         echo "Cannot use interface $INTERFACE_LAN - exiting"
62         exit 1
63     }
64
65     
66     #Getting host IP/masklen
67     address=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $2;}')
68     [ -z "$address" ] && { echo "ERROR: Could not determine IP address for $INTERFACE_LAN" ; exit 1 ; }
69
70 broadcast=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $4;}')
71     [ -z "$broadcast" ] && echo "WARNING: Could not determine broadcast address for $INTERFACE_LAN"
72
73     gateway=$(netstat -rn | grep '^0.0.0.0' | awk '{print $2;}')
74     [ -z "$gateway" ] && echo "WARNING: Could not determine gateway IP"
75
76     # creating the bridge
77     echo "Creating bridge INTERFACE_BRIDGE=$INTERFACE_BRIDGE"
78     brctl addbr $INTERFACE_BRIDGE
79     #brctl stp $INTERFACE_BRIDGE yes
80     brctl addif $INTERFACE_BRIDGE $INTERFACE_LAN
81     echo "Activating promiscuous mode INTERFACE_LAN=$INTERFACE_LAN"
82     /sbin/ifconfig $INTERFACE_LAN 0.0.0.0 promisc up
83     sleep 2
84     echo "Setting bridge address=$address broadcast=$broadcast"
85     # static
86     #/sbin/ifconfig $INTERFACE_BRIDGE $address broadcast $broadcast up
87     dhclient $INTERFACE_BRIDGE
88     sleep 1
89
90     #Reconfigure the routing table
91     echo "Configuring gateway=$gateway"
92     route add default gw $gateway
93
94     echo "========== $COMMAND: exiting start - beg"
95     ifconfig
96     netstat -rn
97     echo "========== $COMMAND: exiting start - end"
98
99
100 return 0
101
102 }
103
104
105 function failure () {
106     echo "$COMMAND : Bailing out"
107     exit 1
108 }
109
110 function cidr_notation () {
111
112 netmask=$1; shift
113 cidr=0
114 for i in $(seq 1 4) ; do
115     part=$(echo $netmask | cut -d. -f $i)
116     case $part in
117         "255") cidr=$((cidr + 8));;
118         "254") cidr=$((cidr + 7));;
119         "252") cidr=$((cidr + 6));;
120         "248") cidr=$((cidr + 5));;
121         "240") cidr=$((cidr + 4));;
122         "224") cidr=$((cidr + 3));;
123         "192") cidr=$((cidr + 2));;
124         "128") cidr=$((cidr + 1));;
125         "0") cidr=$((cidr + 0));;
126      esac
127 done
128 echo $cidr
129
130 }
131
132 function check_yum_installed () {
133     package=$1; shift
134     rpm -q $package >& /dev/null || yum -y install $package
135 }
136
137 function check_yumgroup_installed () {
138     group="$1"; shift
139     yum grouplist "$group" | grep -q Installed || { yum -y groupinstall "$group" ; }
140 }
141
142 function prepare_host() {
143         
144     #################### lxc-tools : rebuild as current fedora release has flaws
145     #install development tools
146     check_yumgroup_installed "Development Tools"
147     #install libcap-devel, libvirt
148     check_yum_installed libcap-devel
149     check_yum_installed libvirt
150
151     #retrieve and install lxc from sources 
152     raw_version=$(lxc-version ||: )
153     lxc_installed_version=$(echo $raw_version | sed -e 's,.*: ,,')
154     if [ "$lxc_installed_version" != "$lxc_version" ] ; then
155         echo "Expecting version" '['$lxc_version']'
156         echo "Found version" '['$lxc_installed_version']'
157         echo "Installing lxc ..."
158         cd /root
159         [ -d lxc ] || git clone "$lxc_git_repo"
160         cd lxc
161         git pull
162         git checkout $lxc_version
163         ./autogen.sh
164         ./configure --prefix=/usr --exec-prefix=/usr
165         make
166         make install
167         mkdir -p /usr/var/lib/
168         [ -d /usr/var/lib/lxc ] || ln -s /var/lib/lxc /usr/var/lib/lxc
169         cd $BUILD_DIR
170     fi
171  
172 #    #create a placeholder (just a hack to make lxc works)
173 #    [ -d "/usr/local/var/lib" ] || mkdir -p /usr/local/var/lib
174
175     #################### bride initialization
176     check_yum_installed bridge-utils
177     #Bridge init
178     isInstalled=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
179     if [ "$isInstalled" != "br0" ] ; then
180         bridge_init
181         sleep 5
182     fi
183
184     return 0
185 }
186
187
188
189 function configure_fedora() {
190
191     # disable selinux in fedora
192     mkdir -p $rootfs_path/selinux
193     echo 0 > $rootfs_path/selinux/enforce
194
195    # configure the network 
196
197     cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$IFNAME
198 DEVICE=$IFNAME
199 BOOTPROTO=static
200 ONBOOT=yes
201 HOSTNAME=$HOSTNAME
202 IPADDR=$IP
203 NETMASK=$NETMASK
204 GATEWAY=$GATEWAY
205 NM_CONTROLLED=no
206 TYPE=Ethernet
207 MTU=1500
208 EOF
209
210 # set the hostname
211     cat <<EOF > ${rootfs_path}/etc/sysconfig/network
212 NETWORKING=yes
213 HOSTNAME=$HOSTNAME
214 EOF
215
216     # set minimal hosts
217 #    cat <<EOF > $rootfs_path/etc/hosts
218 #127.0.0.1 localhost $HOSTNAME
219 #EOF
220
221     dev_path="${rootfs_path}/dev"
222     rm -rf $dev_path
223     mkdir -p $dev_path
224     mknod -m 666 ${dev_path}/null c 1 3
225     mknod -m 666 ${dev_path}/zero c 1 5
226     mknod -m 666 ${dev_path}/random c 1 8
227     mknod -m 666 ${dev_path}/urandom c 1 9
228     mkdir -m 755 ${dev_path}/pts
229     mkdir -m 1777 ${dev_path}/shm
230     mknod -m 666 ${dev_path}/tty c 5 0
231     mknod -m 666 ${dev_path}/tty0 c 4 0
232     mknod -m 666 ${dev_path}/tty1 c 4 1
233     mknod -m 666 ${dev_path}/tty2 c 4 2
234     mknod -m 666 ${dev_path}/tty3 c 4 3
235     mknod -m 666 ${dev_path}/tty4 c 4 4
236     mknod -m 600 ${dev_path}/console c 5 1
237     mknod -m 666 ${dev_path}/full c 1 7
238     mknod -m 600 ${dev_path}/initctl p
239     mknod -m 666 ${dev_path}/ptmx c 5 2
240
241     #echo "setting root passwd to $root_password"
242     #echo "root:$root_password" | chroot $rootfs_path chpasswd
243
244     return 0
245 }
246
247
248 function configure_fedora_init() {
249
250     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
251     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
252     chroot ${rootfs_path} chkconfig udev-post off
253     chroot ${rootfs_path} chkconfig network on
254 }
255
256
257 function configure_fedora_systemd() {
258
259     unlink ${rootfs_path}/etc/systemd/system/default.target
260     touch ${rootfs_path}/etc/fstab
261     chroot ${rootfs_path} ln -s /dev/null //etc/systemd/system/udev.service
262     chroot ${rootfs_path} ln -s /lib/systemd/system/multi-user.target /etc/systemd/system/default.target
263     #dependency on a device unit fails it specially that we disabled udev
264     sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
265     chroot ${rootfs_path} chkconfig network on
266 }
267
268 function download_fedora() {
269 set -x
270     # check the mini fedora was not already downloaded
271     INSTALL_ROOT=$cache/partial
272     echo $INSTALL_ROOT
273     mkdir -p $INSTALL_ROOT
274     if [ $? -ne 0 ]; then
275         echo "Failed to create '$INSTALL_ROOT' directory"
276         return 1
277     fi
278
279     # download a mini fedora into a cache
280     echo "Downloading fedora minimal ..."
281     YUM="yum --installroot $INSTALL_ROOT -y --nogpgcheck --releasever=$release"
282     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
283   
284     
285     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
286     RELEASE_URL="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
287     echo "Fetching from $RELEASE_URL"
288     curl -f "$RELEASE_URL" > $INSTALL_ROOT/fedora-release-$release.noarch.rpm
289     
290     mkdir -p $INSTALL_ROOT/var/lib/rpm
291     rpm --root $INSTALL_ROOT  --initdb
292     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm
293     echo "$YUM install $PKG_LIST"
294     $YUM install $PKG_LIST
295
296     if [ $? -ne 0 ]; then
297         echo "Failed to download the rootfs, aborting."
298         return 1
299     fi
300
301     mv "$INSTALL_ROOT" "$cache/rootfs"
302     echo "Download complete."
303
304     return 0
305 }
306
307
308 function copy_fedora() {
309 set -x
310     # make a local copy of the minifedora
311     echo -n "Copying rootfs to $rootfs_path ..."
312     mkdir -p $rootfs_path
313     rsync -a $cache/rootfs/ $rootfs_path/
314     return 0
315 }
316
317
318 function update_fedora() {
319 set -x
320     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
321     $YUM update
322 }
323
324
325 function install_fedora() {
326     set -x
327
328     mkdir -p /var/lock/subsys/
329     (
330         flock -n -x 200
331         if [ $? -ne 0 ]; then
332             echo "Cache repository is busy."
333             return 1
334         fi
335
336         echo "Checking cache download in $cache/rootfs ... "
337         if [ ! -e "$cache/rootfs" ]; then
338             download_fedora
339             if [ $? -ne 0 ]; then
340                 echo "Failed to download 'fedora base'"
341                 return 1
342             fi
343         else
344             echo "Cache found. Updating..."
345             update_fedora
346             if [ $? -ne 0 ]; then
347                 echo "Failed to update 'fedora base', continuing with last known good cache"
348             else
349                 echo "Update finished"
350             fi
351         fi
352
353         echo "Copy $cache/rootfs to $rootfs_path ... "
354         copy_fedora
355         if [ $? -ne 0 ]; then
356             echo "Failed to copy rootfs"
357             return 1
358         fi
359
360         return 0
361
362         ) 200>/var/lock/subsys/lxc
363
364     return $?
365 }
366
367
368 function copy_configuration() {
369
370     mkdir -p $config_path
371     cat <<EOF >> $config_path/config
372 lxc.utsname = $lxc
373 lxc.arch = $arch2
374 lxc.tty = 4
375 lxc.pts = 1024
376 lxc.rootfs = $rootfs_path
377 lxc.mount  = $config_path/fstab
378 #networking
379 lxc.network.type = $lxc_network_type
380 lxc.network.flags = up
381 lxc.network.link = $lxc_network_link
382 lxc.network.name = $IFNAME
383 lxc.network.mtu = 1500
384 lxc.network.ipv4 = $IP/$CIDR
385 lxc.network.veth.pair = $veth_pair
386 #cgroups
387 #lxc.cgroup.devices.deny = a
388 # /dev/null and zero
389 lxc.cgroup.devices.allow = c 1:3 rwm
390 lxc.cgroup.devices.allow = c 1:5 rwm
391 # consoles
392 lxc.cgroup.devices.allow = c 5:1 rwm
393 lxc.cgroup.devices.allow = c 5:0 rwm
394 lxc.cgroup.devices.allow = c 4:0 rwm
395 lxc.cgroup.devices.allow = c 4:1 rwm
396 # /dev/{,u}random
397 lxc.cgroup.devices.allow = c 1:9 rwm
398 lxc.cgroup.devices.allow = c 1:8 rwm
399 lxc.cgroup.devices.allow = c 136:* rwm
400 lxc.cgroup.devices.allow = c 5:2 rwm
401 # rtc
402 lxc.cgroup.devices.allow = c 254:0 rwm
403 lxc.cgroup.devices.allow = b 255:0 rwm
404 EOF
405
406
407
408     cat <<EOF > $config_path/fstab
409 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
410 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
411 sysfs           $rootfs_path/sys          sysfs defaults  0 0
412 EOF
413     if [ $? -ne 0 ]; then
414         echo "Failed to add configuration"
415         return 1
416     fi
417
418     return 0
419 }
420
421
422
423
424 # overwrite lxc's internal yum config
425 function configure_yum_in_lxc () {
426     set -x 
427     set -e 
428     trap failure ERR INT
429
430     lxc=$1; shift
431     fcdistro=$1; shift
432     pldistro=$1; shift
433
434     echo "Initializing yum.repos.d in $lxc"
435     rm -f $rootfs_path/etc/yum.repos.d/*
436
437     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
438 [fedora]
439 name=Fedora $release - \$basearch
440 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/\$basearch/os/
441 enabled=1
442 metadata_expire=7d
443 gpgcheck=1
444 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
445
446 [updates]
447 name=Fedora $release - \$basearch - Updates
448 baseurl=http://mirror.onelab.eu/fedora/updates/$release/\$basearch/
449 enabled=1
450 metadata_expire=7d
451 gpgcheck=1
452 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
453 EOF
454     
455     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
456     # just mention 'none' as the repo url
457     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
458         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
459             echo "WARNING : cannot create myplc repo"
460         else
461             # exclude kernel from fedora repos 
462             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
463             for repo in $rootfs_path/etc/yum.repos.d/* ; do
464                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
465             done
466             # the build repo is not signed at this stage
467             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
468 [myplc]
469 name= MyPLC
470 baseurl=$REPO_URL
471 enabled=1
472 gpgcheck=0
473 EOF
474         fi
475     fi
476 }    
477
478 # return yum or debootstrap
479 function package_method () {
480     fcdistro=$1; shift
481     case $fcdistro in
482         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
483         lenny|etch) echo debootstrap ;;
484         *) echo Unknown distro $fcdistro ;;
485     esac 
486 }
487
488 # return arch from debian distro and personality
489 function canonical_arch () {
490     personality=$1; shift
491     fcdistro=$1; shift
492     case $(package_method $fcdistro) in
493         yum)
494             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
495         debootstrap)
496             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
497         *)
498             echo Unknown-arch-3 ;;
499     esac
500 }
501
502 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
503 function almost_empty () { 
504     dir="$1"; shift ; 
505     # non existing is fine
506     [ ! -d $dir ] && return 0; 
507     # need to have at most one file
508     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
509 }
510
511 function setup_lxc() {
512
513     set -x
514     set -e
515     #trap failure ERR INT
516
517     lxc=$1; shift
518     fcdistro=$1; shift
519     pldistro=$1; shift
520     personality=$1; shift
521
522     # create lxc container 
523     copy_configuration
524     if [ $? -ne 0 ]; then
525         echo "failed write configuration file"
526         exit 1
527     fi
528
529     install_fedora
530     if [ $? -ne 0 ]; then
531         echo "failed to install fedora"
532         exit 1
533     fi
534
535     configure_fedora
536     if [ $? -ne 0 ]; then
537         echo "failed to configure fedora for a container"
538         exit 1
539     fi
540
541     type /bin/systemd >/dev/null 2>&1
542     if [ $? -ne 0 ]; then
543         configure_fedora_init
544     else
545         configure_fedora_systemd
546     fi
547
548     # Enable cgroup
549     mkdir $rootfs_path/cgroup
550     
551     # set up resolv.conf
552     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
553     # and /etc/hosts for at least localhost
554     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
555     
556     # ssh access to lxc
557     mkdir $rootfs_path/root/.ssh
558     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
559     
560     # start container
561     lxc-start -d -n $lxc
562
563     lxc-wait -n $lxc -s RUNNING
564
565     echo $IP is up, waiting for ssh...
566
567     # wait max 5 min for sshd to start 
568     ssh_up=""
569     stop_time=$(($(date +%s) + 300))
570     current_time=$(date +%s)
571
572     while [ "$current_time" -lt "$stop_time" ] ; do
573          echo "ssh attempt ..."
574          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
575          sleep 10
576          current_time=$(($current_time + 10))
577     done
578
579     [ -z $ssh_up ] && echo "SSHD in container $lxc is not running"
580      
581
582     # rpm --rebuilddb
583     chroot $rootfs_path rpm --rebuilddb
584     #ssh -o "StrictHostKeyChecking no" $IP "rpm --rebuilddb"
585
586     configure_yum_in_lxc $lxc $fcdistro $pldistro
587
588     return 0
589 }
590
591 function devel_or_vtest_tools () {
592
593     set -x 
594     set -e 
595     trap failure ERR INT
596
597     lxc=$1; shift
598     fcdistro=$1; shift
599     pldistro=$1; shift
600     personality=$1; shift
601
602     pkg_method=$(package_method $fcdistro)
603
604     # check for .pkgs file based on pldistro
605     if [ -n "$VBUILD_MODE" ] ; then
606         pkgsname=devel.pkgs
607     else
608         pkgsname=vtest.pkgs
609     fi
610     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
611
612     ### install individual packages, then groups
613     # get target arch - use uname -i here (we want either x86_64 or i386)
614    
615     lxc_arch=$(chroot $rootfs_path uname -i)
616     # on debian systems we get arch through the 'arch' command
617     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path arch)
618
619     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
620     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
621
622     case "$pkg_method" in
623         yum)
624             [ -n "$packages" ] && chroot $rootfs_path yum -y install $packages
625             for group_plus in $groups; do
626                 group=$(echo $group_plus | sed -e "s,+++, ,g")
627                 chroot $rootfs_path yum -y groupinstall "$group"
628             done
629             # store current rpm list in /init-lxc.rpms in case we need to check the contents
630             chroot $rootfs_path rpm -aq > $rootfs_path/init-lxc.rpms
631             ;;
632         debootstrap)
633             chroot $rootfs_path apt-get update
634             for package in $packages ; do 
635                 chroot $rootfs_path  apt-get install -y $package 
636             done
637             ### xxx todo install groups with apt..
638             ;;
639         *)
640             echo "unknown pkg_method $pkg_method"
641             ;;
642     esac
643
644     return 0
645 }
646
647 function post_install () {
648     if [ -n "$VBUILD_MODE" ] ; then
649         post_install_vbuild "$@" 
650     else
651         post_install_myplc "$@"
652     fi
653     # setup localtime from the host
654     lxc=$1; shift 
655     cp /etc/localtime $rootfs_path/etc/localtime
656 }
657
658 function post_install_vbuild () {
659
660     set -x 
661     set -e 
662     trap failure ERR INT
663
664     lxc=$1; shift
665     personality=$1; shift
666
667 ### From myplc-devel-native.spec
668 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
669     cat << EOF | chroot $rootfs_path bash -x
670     # set up /dev/loop* in lxc
671     for i in \$(seq 0 255) ; do
672         mknod -m 640 /dev/loop\$i b 7 \$i
673     done
674     
675     # create symlink for /dev/fd
676     [ ! -e "/dev/fd" ] && ln -s /proc/self/fd /dev/fd
677
678     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
679     sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
680     if [ -h "/sbin/new-kernel-pkg" ] ; then
681         filename=\$(readlink -f /sbin/new-kernel-pkg)
682         if [ "\$filename" == "/sbin/true" ] ; then
683                 echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
684                 echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
685                 echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
686                 exit 1
687         fi
688     fi
689     
690     # customize root's prompt
691     cat << PROFILE > /root/.profile
692 export PS1="[$lxc] \\w # "
693 PROFILE
694
695     uid=2000
696     gid=2000
697     
698     # add a "build" user to the system
699     builduser=\$(grep "^build:" /etc/passwd | wc -l)
700     if [ \$builduser -eq 0 ] ; then
701         groupadd -o -g \$gid build;
702         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
703     fi
704
705 # Allow build user to build certain RPMs as root
706     if [ -f /etc/sudoers ] ; then
707         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
708         if [ \$buildsudo -eq 0 ] ; then
709             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
710         fi
711         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
712     fi
713 #
714 EOF
715
716 }
717
718 function post_install_myplc  () {
719     set -x 
720     set -e 
721     trap failure ERR INT
722
723     lxc=$1; shift
724     personality=$1; shift
725
726 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
727     cat << EOF | chroot $rootfs_path bash -x
728
729     # create /etc/sysconfig/network if missing
730     [ -f /etc/sysconfig/network ] || echo NETWORKING=yes > /etc/sysconfig/network
731
732     # create symlink for /dev/fd
733     [ ! -e "/dev/fd" ] && ln -s /proc/self/fd /dev/fd
734
735     # turn off regular crond, as plc invokes plc_crond
736     chkconfig crond off
737
738     # take care of loginuid in /etc/pam.d 
739     sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
740
741     # customize root's prompt
742     cat << PROFILE > /root/.profile
743 export PS1="[$lxc] \\w # "
744 PROFILE
745
746 EOF
747 }
748
749 function usage () {
750     set +x 
751     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
752     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
753     echo "Description:"
754     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
755     echo "Supported options"
756     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
757     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
758     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
759     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
760     echo "-- lxc-options"
761     echo "  --netdev : interface to be defined inside lxc"
762     echo "  --interface : IP to be defined for the lxc"
763     echo "  --hostname : Hostname to be defined for the lxc"
764     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
765     echo "   myplc.repo does not get created"
766     exit 1
767 }
768
769 ### parse args and 
770 function main () {
771
772     #set -e
773     #trap failure ERR INT
774
775     case "$COMMAND" in
776         $COMMAND_VBUILD)
777             VBUILD_MODE=true ;;
778         $COMMAND_MYPLC)
779             MYPLC_MODE=true;;
780         *)
781             usage ;;
782     esac
783
784     VERBOSE=
785     RESISTANT=""
786     IFNAME=""
787     LXC_OPTIONS=""
788     while getopts "f:d:p:i:" opt ; do
789         case $opt in
790             f) fcdistro=$OPTARG;;
791             d) pldistro=$OPTARG;;
792             p) personality=$OPTARG;;
793             i) IFNAME=$OPTARG;;
794             *) usage ;;
795         esac
796     done
797         
798     shift $(($OPTIND - 1))
799
800     # parse fixed arguments
801     [[ -z "$@" ]] && usage
802     lxc=$1 ; shift
803     if [ -n "$MYPLC_MODE" ] ; then
804         [[ -z "$@" ]] && usage
805         REPO_URL=$1 ; shift
806     fi
807
808     # parse vserver options
809     if [[ -n "$@" ]] ; then
810         if [ "$1" == "--" ] ; then
811             shift
812             LXC_OPTIONS="$@"
813         else
814             usage
815         fi
816     fi
817
818     eval set -- "$LXC_OPTIONS"
819
820     while true
821      do
822         case "$1" in
823              --netdev)      IFNAME=$2; shift 2;;
824              --interface)   IP=$2; shift 2;;
825              --hostname)    HOSTNAME=$2; shift 2;;
826              *)             break ;;
827         esac
828       done
829
830    
831     if [ -n "$VBUILD_MODE" ] ; then
832         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
833         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
834     fi
835
836     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
837     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
838     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
839     
840     release=$(echo $fcdistro | cut -df -f2)
841
842     if [ "$personality" == "linux32" ]; then
843         arch=i386
844         arch2=x86
845     elif [ "$personality" == "linux64" ]; then
846         arch=x86_64
847         arch2=x86_64
848     else
849         echo "Unknown personality: $personality"
850     fi
851
852     # need lxc installed before we can run lxc-ls
853     # need bridge installed
854     prepare_host    
855
856     if [ -n "$VBUILD_MODE" ] ; then
857
858         # Bridge IP affectation
859         x=$(echo $personality | cut -dx -f2)
860         y=$(echo $fcdistro | cut -df -f2)
861         z=$(($x + $y))
862
863         IP="192.168.122.$z"
864         NETMASK="255.255.255.0"
865         GATEWAY="192.168.122.1"
866         
867         lxc_network_type=veth
868         lxc_network_link=virbr0
869         veth_pair="veth$z"
870         echo "the IP address of container $lxc is $IP "
871     else
872         [[ -z "$REPO_URL" ]] && usage
873         [[ -z "$IP" ]] && usage
874         NETMASK=$(ifconfig br0 | grep 'inet addr' | awk '{print $4}' | sed -e 's/.*://')
875         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
876         [[ -z "$HOSTNAME" ]] && usage
877         lxc_network_type=veth
878         lxc_network_link=br0
879         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
880     fi
881
882     CIDR=$(cidr_notation $NETMASK)
883     
884
885     if [ "$(id -u)" != "0" ]; then
886           echo "This script should be run as 'root'"
887           exit 1
888     fi
889
890     path=/var/lib/lxc
891     rootfs_path=$path/$lxc/rootfs
892     config_path=$path/$lxc
893     cache_base=/var/cache/lxc/fedora/$arch
894     cache=$cache_base/$release
895     root_password=root
896     
897     # check whether the rootfs directory is created to know if the container exists
898     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
899     [ -d $rootfs_path ] && { echo "container $lxc already exists - exiting" ; exit 1 ; }
900
901     setup_lxc $lxc $fcdistro $pldistro $personality 
902
903     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
904
905     post_install $lxc $personality
906     
907
908     echo $COMMAND Done
909 }
910
911 main "$@"