#!/bin/bash -e
# Copyright (c) 2007 RightScale Inc. 
#  
# Permission is hereby granted, free of charge, to any person obtaining 
# a copy of this software and associated documentation files (the 
# "Software"), to deal in the Software without restriction, including 
# without limitation the rights to use, copy, modify, merge, publish, 
# distribute, sublicense, and/or sell copies of the Software, and to 
# permit persons to whom the Software is furnished to do so, subject to 
# the following conditions: 
#  
# The above copyright notice and this permission notice shall be 
# included in all copies or substantial portions of the Software. 
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Uncomment and edit these for production use
# the full pathname is required for the certificates and 
# private keys. Examples are below. 
#
#export EC2_CERT=/home/ec2/etc/cert.pem
#export EC2_HOME=/home/ec2 
#export EC2_PRIVATE_KEY=/home/ec2/etc/pk.pem
#export AWS_ACCOUNT_NUMBER=
#export AWS_ACCESS_KEY_ID= 
#export AWS_SECRET_ACCESS_KEY=
#export AWS_BUCKET=
#export IMAGE_NAME=
#export KERNEL_ID=

echo "Hello $USER, Lets get started installing CentOS 5"

echo "........................................" 
showOpts () {
	echo "Please Select an Option or 8 to quit"
	echo "0) Set EC2 Variables"
	echo "1) Create and Mount Image"
	echo "2) Installing Yum and CentOS 5 Base"
	echo "3) Install Additional Packages"
	echo "4) Install RightScale Customizations"
	echo "5) Clean Up FileSystem and Bundle Image"
	echo "6) Upload Image"
	echo "7) Clean Up"
	echo "8) Quit"
}
showEC2Opts () {

	echo "Please Select an Option or 4 to quit"
	echo "1) Set EC2 Variables"
	echo "2) Show EC2 Variables"
	echo "3) Set AWS Bucket, Image Name & Kernel ID"
	echo "4) Back"
}

while [ 1 ] 
do
	showOpts
	read CHOICE
	case "$CHOICE" in
		"0")
			while [ 1 ]
			do
			showEC2Opts
			read EC2CHOICE
			case "$EC2CHOICE" in
				"1")
					echo "Warning !!!"
					echo "The full pathname is required for the Certificate"
					echo "and Private Keys to work properly"
					echo " "
			   		echo "Please Enter Your Certificate Path"
			   		read EC2_CERT_PATH
			   		export EC2_CERT=$EC2_CERT_PATH
			   		echo "Please Enter You Private Key Path"
			   		read EC2_PRIVATE_KEY_PATH
			   		export EC2_PRIVATE_KEY=$EC2_PRIVATE_KEY_PATH
			   		echo "Please Enter Your AWS Account Number"
			   		read  AWS_ACCOUNT_NUMBER_TEMP
			   		export AWS_ACCOUNT_NUMBER=$AWS_ACCOUNT_NUMBER_TEMP
			   		echo "Please Enter Your AWS Access Key"
			   		read AWS_ACCESS_KEY_ID_TEMP
			   		export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID_TEMP
			   		echo "Please Enter Your AWS Secret Access Key"
			   		read AWS_SECRET_ACCESS_KEY_TEMP
			   		export AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY_TEMP
			   		echo "Done"
			   					   		
			   		;;
			   	"2")
			   		echo "------------Parameters-----------------------"
			   		echo "EC2 Certificate Path:" $EC2_CERT
			   		echo "EC2 Private Key Path:" $EC2_PRIVATE_KEY
			   		echo "AWS Account Number:" $AWS_ACCOUNT_NUMBER
			   		echo "AWS Access Key:" $AWS_ACCESS_KEY_ID
			   		echo "AWS Secret Access Key:" $AWS_SECRET_ACCESS_KEY
			   		echo "AWS Bucket:" $AWS_BUCKET
			   		echo "Image Name:" $IMAGE_NAME
			   		echo "Kernel ID:" $KERNEL_ID
			   		echo "------------End Parameters-------------------"
			   		echo ""
			   		;;
					
				"3")
					echo "Please enter in the AWS Bucket"
			   		read AWS_BUCKET_TEMP
			   		export AWS_BUCKET=$AWS_BUCKET_TEMP
			   		echo "Please Enter Your Image Name ex: myfc6.img"
			   		read IMAGE_NAME_TEMP
			   		export IMAGE_NAME=$IMAGE_NAME_TEMP
			   	  echo "Please Enter Your Kernel ID ex: myfc6.img"
			   		read KERNEL_ID_TEMP
			   		export KERNEL_ID=$KERNEL_ID_TEMP
					showEC2Opts
					;;
				"4")
					break
					;;
			esac
			done
			;;
		"1")
			echo "Creating 10GB Image"
			mkdir /mnt/image
			dd if=/dev/zero of=/mnt/image/$IMAGE_NAME bs=1M count=10240
			echo "Creating File System"
			mke2fs -F -j /mnt/image/$IMAGE_NAME
			mkdir /mnt/ec2-fs
			echo "Mounting File System in /mnt/ec2-fs"
			mount -o loop /mnt/image/$IMAGE_NAME /mnt/ec2-fs
			mkdir /mnt/ec2-fs/dev
			/sbin/MAKEDEV -d /mnt/ec2-fs/dev -x console
			/sbin/MAKEDEV -d /mnt/ec2-fs/dev -x null
			/sbin/MAKEDEV -d /mnt/ec2-fs/dev -x zero
			mkdir /mnt/ec2-fs/proc
			mount -t proc none /mnt/ec2-fs/proc
			mkdir /mnt/ec2-fs/etc
			cat <<EOL > /mnt/ec2-fs/etc/fstab
/dev/sda1  /         ext3    defaults        1 1
/dev/sda2  /mnt      ext3    defaults        1 2
/dev/sda3  swap      swap    defaults        0 0
none       /dev/pts  devpts  gid=5,mode=620  0 0
none       /dev/shm  tmpfs   defaults        0 0
none       /proc     proc    defaults        0 0
none       /sys      sysfs   defaults        0 0
rpc_pipefs /var/lib/nfs/rpc_pipefs rpc_pipefs defaults 0 0
EOL
			echo "Finished Step 1"	
			;;
		"2")
			echo "Installing Yum 3.0"
			wget http://linux.duke.edu/projects/yum/download/3.0/yum-3.0.5.tar.gz
			tar -xvzf yum-3.0.5.tar.gz
			cd yum-3.0.5
			make DESTDIR=/ install
			echo "Creating Yum Confuration"
			mkdir -p /mnt/ec2-fs/sys/block
			mkdir -p /mnt/ec2-fs/var/
			mkdir -p /mnt/ec2-fs/var/log/
			touch /mnt/ec2-fs/var/log/yum.log
			cat <<EOL > /mnt/image/yum.conf
[main]
cachedir=/var/cache/yum
debuglevel=2
logfile=/var/log/yum.log
exclude=*-debuginfo
gpgcheck=0
obsoletes=1
pkgpolicy=newest
distroverpkg=redhat-release
tolerant=1
exactarch=1
reposdir=/dev/null
metadata_expire=1800

[base]
name=CentOS 5 - $basearch - Base
baseurl=http://mirror.rightscale.com/centos/5.0/os/i386/
enabled=1

[updates-released]
name=CentOS 5 - $basearch - Released Updates
baseurl=http://mirror.rightscale.com/centos/5.0/updates/i386/
enabled=1

[extras]
name=CentOS 5 Extras $releasever - $basearch
baseurl=http://vault.centos.org/5.0/extras/i386/
enabled=1

[epel]
name=Extra Packages for Enterprise Linux 5 - $basearch
baseurl=http://download.fedora.redhat.com/pub/epel/5/i386
mirrorlist=http://mirrors.fedoraproject.org/mirrorlist?repo=epel-5&arch=i386
failovermethod=priority
enabled=1

[rightscale]
name=RightScale Packages for Enterprise Linux 5 - $basearch
baseurl=http://mirror.rightscale.com/rightscale_software/centos/5/i386/
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=
# set metadata to expire faster then main
metadata_expire=300

EOL
			echo "Running Yum"
			yum -c /mnt/image/yum.conf --installroot=/mnt/ec2-fs -y groupinstall Base
			echo "Finished Step 2"
			;;
		"3")
			echo "Starting Secondary Install"
			yum -c /mnt/image/yum.conf --installroot=/mnt/ec2-fs -y install wget mlocate nano logrotate ruby* syslog-ng postfix openssl openssh openssh-askpass openssh-clients openssh-server curl gcc* zip unzip bison flex compat-libstdc++-296 cvs subversion autoconf automake libtool compat-gcc-34-g77 mutt sysstat rpm-build fping vim-common vim-enhanced rrdtool rrdtool-devel rrdtool-doc rrdtool-perl rrdtool-python rrdtool-ruby rrdtool-tcl pkgconfig lynx screen yum-utils bwm-ng createrepo
			yum -c /mnt/image/yum.conf --installroot=/mnt/ec2-fs -y clean packages
			cat <<EOL > /mnt/ec2-fs/etc/sysconfig/network
NETWORKING=yes
HOSTNAME=localhost.localdomain
EOL

			cat <<EOL > /mnt/ec2-fs/etc/sysconfig/network-scripts/ifcfg-eth0
ONBOOT=yes
DEVICE=eth0
BOOTPROTO=dhcp
EOL

			cat <<EOL >> /mnt/ec2-fs/etc/rc.local
touch /var/lock/subsys/local
# Update the EC2 AMI creation tools
#echo " + Updating ec2-ami-tools"
#curl -o /tmp/ec2-ami-tools.noarch.rpm http://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.noarch.rpm && \
#rpm -Uvh /tmp/ec2-ami-tools.noarch.rpm && \
#echo " + Updated ec2-ami-tools"



EOL
			cat <<EOL >> /mnt/ec2-fs/etc/ssh/sshd_config
UseDNS  no
PermitRootLogin without-password
EOL

			echo "Finished Step 3"
			;;
		"4")
			echo "Adding RightScale"
			mkdir -p /tmp/updates
			mkdir -p /mnt/ec2-fs/opt/rightscale/
			mkdir -p /mnt/ec2-fs/opt/rightscale/bin
			mkdir -p /mnt/ec2-fs/opt/rightscale/etc
			mkdir -p /mnt/ec2-fs/opt/rightscale/etc/init.d
			mkdir -p /mnt/ec2-fs/opt/rightscale/lib
			mkdir -p /mnt/ec2-fs/var/spool/ec2/
			mkdir -p /mnt/ec2-fs/var/spool/ec2/meta-data			
			curl -o /tmp/updates/ec2-ami-tools.noarch.rpm http://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.noarch.rpm
			rpm -Uvh /tmp/updates/ec2-ami-tools.noarch.rpm --force --nodeps
			#fetch needed packages
			echo "Fetch Needed Packages"
		  curl -o /tmp/updates/linux-2.6.16-ec2.tgz http://s3.amazonaws.com/ec2-downloads/linux-2.6.16-ec2.tgz
		  curl -o /tmp/updates/xen-3.1.0-src-ec2-v1.0.tgz http://ec2-downloads.s3.amazonaws.com/xen-3.1.0-src-ec2-v1.0.tgz
			curl -o /tmp/kernel-modules.2.6.16-xenU.tgz http://s3.amazonaws.com/rightscale_scripts/kernel-modules.2.6.16-xenU.tgz 
			curl -o /tmp/ec2-modules-2.6.18-xenU-ec2-v1.0-i686.tgz http://ec2-downloads.s3.amazonaws.com/ec2-modules-2.6.18-xenU-ec2-v1.0-i686.tgz
			tar -xzf /tmp/kernel-modules.2.6.16-xenU.tgz -C /mnt/ec2-fs/lib/modules/
			tar -xzf /tmp/ec2-modules-2.6.18-xenU-ec2-v1.0-i686.tgz -C /mnt/ec2-fs/
			rm -fr /tmp/kernel-modules.2.6.16-xenU.tgz
			#chroot Section
			echo "Chroot Time"
			mkdir -p /mnt/ec2-fs/tmp/updates
			touch /mnt/ec2-fs/etc/mtab
			cp -R /tmp/updates/ /mnt/ec2-fs/tmp/
			cat <<'EOL' > /mnt/ec2-fs/tmp/updates/install-script
		

echo "starting install"
echo "127.0.0.1		localhost 	localhost.localdomain" > /etc/hosts
authconfig --enableshadow --useshadow --enablemd5 --updateall
#fix  error
echo 'hwcap 0 nosegneg' > /etc/ld.so.conf.d/libc6-xen.conf
/sbin/ldconfig -v
mv /lib/tls /lib/tls.disabled
#fix logrotate
touch /var/log/boot.log

echo "Disabling TTYs"
perl -p -i -e 's/(.*tty2)/#\1/' /etc/inittab
perl -p -i -e 's/(.*tty3)/#\1/' /etc/inittab
perl -p -i -e 's/(.*tty4)/#\1/' /etc/inittab
perl -p -i -e 's/(.*tty5)/#\1/' /etc/inittab
perl -p -i -e 's/(.*tty6)/#\1/' /etc/inittab
perl -p -i -e 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config 
perl -p -i -e 's/#ClientAliveInterval 0/ClientAliveInterval 60/' /etc/ssh/sshd_config
perl -p -i -e 's/#ClientAliveCountMax 3/ClientAliveCountMax 240/' /etc/ssh/sshd_config
service network start
echo "Fetching RightScale"
cat <<'SSH' >/etc/init.d/getsshkey
#!/bin/bash
# chkconfig: 4 11 11
# description: This script fetches the ssh key early. \
#

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
[ -r /etc/sysconfig/network ] && . /etc/sysconfig/network

# Check that networking is up.
[ "${NETWORKING}" = "no" ] && exit 1

start() {
  if [ ! -d /root/.ssh ] ; then
          mkdir -p /root/.ssh
          chmod 700 /root/.ssh
  fi
  # Fetch public key using HTTP
  curl -f http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/my-key
  if [ $? -eq 0 ] ; then
          cat /tmp/my-key >> /root/.ssh/authorized_keys
          chmod 600 /root/.ssh/authorized_keys
          rm /tmp/my-key
  fi
  # or fetch public key using the file in the ephemeral store:
  if [ -e /mnt/openssh_id.pub ] ; then
          cat /mnt/openssh_id.pub >> /root/.ssh/authorized_keys
          chmod 600 /root/.ssh/authorized_keys
  fi
}

stop() {
  echo "Nothing to do here"
}

restart() {
  stop
  start
}

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  *)
    echo $"Usage: $0 {start|stop}"
    exit 1
esac

exit $?

SSH
chmod +x /etc/init.d/getsshkey

rpm -Uvh http://s3.amazonaws.com/rightscale_scripts/syslog-ng-1.6.12-1.el5.centos.i386.rpm
curl -o /opt/rightscale_scripts.tgz http://s3.amazonaws.com/rightscale_scripts/rightscale_scripts_V3_0_0.tgz
tar -xzf /opt/rightscale_scripts.tgz -C /opt/ 
ln /opt/rightscale/etc/init.d/rightscale /etc/init.d/rightscale
chmod +x /opt/rightscale/etc/init.d/rightscale
chmod +x /etc/init.d/rightscale
echo "Modifying Services"
chkconfig --add rightscale
chkconfig --add postfix
chkconfig --add getsshkey
chkconfig --level 4 getsshkey on
chkconfig --level 4 rightscale on
chkconfig --level 4 postfix on 
chkconfig --level 4 psacct on
chkconfig --level 4 syslog-ng on
chkconfig --level 4 smartd off
chkconfig --level 4 anacron off
chkconfig --level 4 avahi-daemon off
chkconfig --level 4 avahi-dnsconfd off
chkconfig --level 4 apmd off
chkconfig --level 4 acpid off
chkconfig --level 4 auditd off
chkconfig --level 4 irqbalance off
chkconfig --level 4 mdmpd off
chkconfig --level 4 portmap off
chkconfig --level 4 nfslock off
chkconfig --level 4 syslog off
chkconfig --level 4 sendmail off
chkconfig --level 4 cpuspeed off
chkconfig --level 4 cups off
chkconfig --level 4 autofs off
chkconfig --level 4 bluetooth off
chkconfig --level 4 rpcidmapd off
chkconfig --level 4 rpcsvcgssd off
chkconfig --level 4 rpcgssd off
chkconfig --level 4 pcscd off
chkconfig --level 4 gpm off
chkconfig --level 4 hidd off
chkconfig --level 4 xfs off
chkconfig --level 4 yum-updatesd off
chkconfig --del avahi-daemon
chkconfig --del acpid
chkconfig --del auditd
chkconfig --del irqbalance
chkconfig --del mdmpd
chkconfig --del avahi-dnsconfd
chkconfig --del NetworkManager
chkconfig --del NetworkManagerDispatcher
chkconfig --del dhcdbd
chkconfig --del dund
chkconfig --del firstboot
chkconfig --del irda
chkconfig --del apmd
chkconfig --del smartd
chkconfig --del kudzu
chkconfig --del hidd
chkconfig --del gpm
chkconfig --del pcscd
chkconfig --del bluetooth
chkconfig --del cpuspeed
chkconfig --del cups
chkconfig --del rdisc
chkconfig --del sendmail
chkconfig --del readahead_later
chkconfig --del syslog
chkconfig --del wpa_supplicant
chkconfig --del pand
chkconfig --del netplugd


echo "Fetching Java"
curl -o /tmp/updates/jdk-6u4-linux-i586.rpm https://s3.amazonaws.com/rightscale_software/java/jdk-6u4-linux-i586.rpm
curl -o /tmp/updates/sun-javadb-client-10.3.1-4.1.i386.rpm https://s3.amazonaws.com/rightscale_software/java/sun-javadb-client-10.3.1-4.1.i386.rpm
curl -o /tmp/updates/sun-javadb-common-10.3.1-4.1.i386.rpm https://s3.amazonaws.com/rightscale_software/java/sun-javadb-common-10.3.1-4.1.i386.rpm
curl -o /tmp/updates/sun-javadb-core-10.3.1-4.1.i386.rpm https://s3.amazonaws.com/rightscale_software/java/sun-javadb-core-10.3.1-4.1.i386.rpm
curl -o /tmp/updates/sun-javadb-demo-10.3.1-4.1.i386.rpm https://s3.amazonaws.com/rightscale_software/java/sun-javadb-demo-10.3.1-4.1.i386.rpm
curl -o /tmp/updates/sun-javadb-docs-10.3.1-4.1.i386.rpm https://s3.amazonaws.com/rightscale_software/java/sun-javadb-docs-10.3.1-4.1.i386.rpm
curl -o /tmp/updates/sun-javadb-javadoc-10.3.1-4.1.i386.rpm https://s3.amazonaws.com/rightscale_software/java/sun-javadb-javadoc-10.3.1-4.1.i386.rpm
echo "Installing Software"
cd /tmp/updates
#curl -o /tmp/updates/bwm-ng-0.5-1.i386.rpm http://s3.amazonaws.com/rightscale_software/bwm-ng-0.5-1.i386.rpm
curl -o /tmp/updates/monit-4.9-2.el5.rf.i386.rpm https://s3.amazonaws.com/rightscale_software/monit-4.9-2.el5.rf.i386.rpm
rpm -Uvh /tmp/updates/*.rpm --nodeps --force
#unpack source
tar -xzf linux-2.6.16-ec2.tgz
mv linux-2.6.16-xenU/ /usr/src/
tar -xzf xen-3.1.0-src-ec2-v1.0.tgz 
cd xen-3.1.0-src-ec2-v1.0
tar -xjf linux-2.6.18.tar.bz2
cp -R -f -b -v linux-2.6-xen-sparse/* linux-2.6.18/ 
mv linux-2.6.18 /usr/src/linux-2.6.18-xenU-ec2-v1.0
echo "Configuring Java Home" 
echo "export JAVA_HOME=/usr/java/default" >> /etc/profile.d/java.sh
chmod +x /etc/profile.d/java.sh
echo "Add EC2 Tools"
mkdir /home/ec2
mkdir /home/ec2/etc
curl -o /tmp/ec2-api-tools.zip http://s3.amazonaws.com/rightscale_software/ec2-api-tools.zip
unzip /tmp/ec2-api-tools.zip -d /tmp/
mv /tmp/ec2-api-tools-1.2-13740/* /home/ec2/
ln -sf /usr/lib/site_ruby/aes/ /usr/lib/ruby/site_ruby/1.8/aes
rm -fr /tmp/ec2*

chmod -R o-w /home/ec2

echo "More EC2 Mods"
cat <<'PROMPT'> /etc/profile.d/prompt.sh
PS1="[\u@\h:\w] " 
PROMPT
chmod +x /etc/profile.d/prompt.sh
cat <<'EC2'> /etc/profile.d/ec2.sh
export EC2_HOME=/home/ec2 
export EC2_CERT=
export EC2_PRIVATE_KEY=
export AWS_ACCOUNT_NUMBER=
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export PATH=$PATH:/home/ec2/bin/
EC2

chmod +x /etc/profile.d/ec2.sh
ln -f /opt/rightscale/etc/motd /etc/motd
echo "RubyGems"
wget http://rubyforge.org/frs/download.php/29548/rubygems-1.0.1.tgz
tar -xzf rubygems-1.0.1.tgz
cd rubygems-1.0.1
ruby setup.rb
gem source -r http://gems.rubyforge.org
gem source -a http://mirror.rightscale.com

cat <<'GEM'> /root/.gemrc
--- 
:update_sources: true
:verbose: true
:benchmark: false
:backtrace: false
:bulk_threshold: 1000
:sources: 
- http://mirror.rightscale.com
GEM

mkdir -p /tmp/updates
curl -o /tmp/updates/s3sync.gem http://s3.amazonaws.com/rightscale_software/s3sync-1.1.4.gem
gem install /tmp/updates/s3sync.gem
gem install xml-simple net-ssh net-sftp -y --no-ri --no-rdoc
updatedb
#cat <<AMI> /etc/cron.daily/do_amitools_update.sh
#!/bin/bash
#
# do_amitools_update.sh: updates ami-tools to the latest version.. 
#
## Include Files:
#. /var/spool/ec2/meta-data.sh
#. /var/spool/ec2/user-data.sh

# Update the EC2 AMI creation tools
#echo " + Updating ec2-ami-tools"
#curl -o /tmp/ec2-ami-tools.noarch.rpm http://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.noarch.rpm && \
#rpm -Uvh /tmp/ec2-ami-tools.noarch.rpm && \
#echo " + Updated ec2-ami-tools"

## Cleanup FileSystem
#rm -f /tmp/ec2-ami-tools.noarch.rpm
#rm -f /tmp/ec2-ami-tools.noarch.rpm.*

#AMI
#chmod +x /etc/cron.daily/do_amitools_update.sh
rpm -Uvh http://s3.amazonaws.com/rightscale_software/centos-release-5.0-1.0.el5.centos.1.i386.rpm

rm /etc/yum.repos.d/CentOS-Media.repo
curl -o /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL http://download.fedora.redhat.com/pub/epel/RPM-GPG-KEY-EPEL
cat <<'YUM'> /etc/yum.repos.d/CentOS-Base.repo

# CentOS-Base.repo
#
# This file uses a new mirrorlist system developed by Lance Davis for CentOS.
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the 
# remarked out baseurl= line instead.
#
#

[base]
name=CentOS-5.0 - Base
baseurl=http://mirror.rightscale.com/centos/5.0/os/i386/
        http://vault.centos.org/5.0/os/$basearch/
mirrorlist=http://mirrorlist.centos.org/?release=5.0&arch=$basearch&repo=os
failovermethod=priority
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5

[updates]
name=CentOS-5.0 - Updates
baseurl=http://mirror.rightscale.com/centos/5.0/updates/$basearch/
        http://vault.centos.org/5.0/updates/$basearch/
mirrorlist=http://mirrorlist.centos.org/?release=5.0&arch=$basearch&repo=updates
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5

#packages used/produced in the build but not released
[addons]
name=CentOS-5.0 - Addons
baseurl=http://mirror.rightscale.com/centos/5.0/addons/i386/
        http://vault.centos.org/5.0/addons/i386/
mirrorlist=http://mirrorlist.centos.org/?release=5&arch=$basearch&repo=addons
failovermethod=priority
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
baseurl=http://mirror.rightscale.com/centos/5.0/extras/i386/
        http://vault.centos.org/5.0/extras/i386/
mirrorlist=http://mirrorlist.centos.org/?release=5&arch=$basearch&repo=extras
failovermethod=priority
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
baseurl=http://mirror.rightscale.com/centos/5.0/centosplus/i386/
        http://vault.centos.org/5.0/centosplus/i386/
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
failovermethod=priority
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5

#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/
failovermethod=priority
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-5

[epel]
name=Extra Packages for Enterprise Linux 5 - $basearch
baseurl=http://mirror.rightscale.com/epel/5/i386
mirrorlist=http://mirrors.fedoraproject.org/mirrorlist?repo=epel-5&arch=$basea$
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL

YUM

cat <<'EOF'> /etc/yum.repos.d/rightscale.repo

[rightscale]
name=RightScale Packages for Enterprise Linux 5 - $basearch
baseurl=http://mirror.rightscale.com/rightscale_software/centos/5/i386/
enabled=1
gpgcheck=0
gpgkey=
# set metadata to expire faster then main
metadata_expire=30

EOF

cat <<'EOF'> /root/.bashrc
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

EOF

cat <<'EOF'> /root/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
unset USERNAME

EOF

cat <<'EOF'> /root/.bash_logout
# ~/.bash_logout

clear

EOF

touch /root/.bash_logout

cat <<'EOF'>> /etc/profile.d/pkgconfig.sh
export PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/local/lib/pkgconfig
EOF
chmod +x /etc/profile.d/pkgconfig.sh

exit 

EOL
			
			chmod +x /mnt/ec2-fs/tmp/updates/install-script
			chroot /mnt/ec2-fs/ /tmp/updates/install-script
			echo "all Done"
			echo "Cleaning up Image"
	    echo $IMAGE_NAME | sed -e 's/.*\(V[0-9_]*\).*/\1/' > /mnt/ec2-fs/etc/rightscale-release
			rm -fr /mnt/ec2-fs/tmp/updates		
			echo "Finished Step 4"
			;;
		"5")
			echo "Prepping for upload"
			sync
			#umount -dlf /mnt/ec2-fs/proc
			#umount -dlf /mnt/ec2-fs
			echo "Bundling Image"
			#ec2-bundle-image -i /mnt/image/$IMAGE_NAME -k $EC2_PRIVATE_KEY -c $EC2_CERT -u $AWS_ACCOUNT_NUMBER
			mkdir -p /mnt/tmp
			if [ -z "$KERNEL_ID" ]; then
			  ec2-bundle-vol -v /mnt/ec2-fs -d /mnt/tmp -p $IMAGE_NAME -k $EC2_PRIVATE_KEY -c $EC2_CERT -u $AWS_ACCOUNT_NUMBER --fstab /mnt/ec2-fs/etc/fstab -r i386
			else 
			  ec2-bundle-vol -v /mnt/ec2-fs -d /mnt/tmp -p $IMAGE_NAME -k $EC2_PRIVATE_KEY -c $EC2_CERT -u $AWS_ACCOUNT_NUMBER --fstab /mnt/ec2-fs/etc/fstab -r i386 --kernel $KERNEL_ID
		  fi
			echo "Finished Step 5"
			;;
		"6")
			echo "Uploading"
			ec2-upload-bundle -b $AWS_BUCKET -m /mnt/tmp/$IMAGE_NAME.manifest.xml -a $AWS_ACCESS_KEY_ID -s $AWS_SECRET_ACCESS_KEY --retry 5
			echo "Finished Step 6"
			;;
		"7")
			echo "Cleanup"
			umount /mnt/ec2-fs/proc
			umount /mnt/ec2-fs
			rm -fr /mnt/image/
			rm -fr /mnt/ec2-fs
			echo "File System Cleaned"
			echo "Finished Step 7"
			;;
		"8")
			exit
			;;
	esac 
done

