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