#!//bin/sh

__delete_all_partition()
{
    DISK=$1
    FDISK_TMP=/tmp/.fdisk.$$

    num=0
    last=0

    PART_LIST=`ls ${DISK}[0-9]* 2> /dev/null`

    if [ -z "$PART_LIST" ]; then
	return
    fi

    for part in $PART_LIST
    do
	last=$((last+1))
    done

    for part in $PART_LIST
    do
	num=$((num+1))

	partnum=${part#${DISK}}

	if [ $num -eq $last ]; then
	    echo -ne "d\nw\n"           >> $FDISK_TMP
	else
	    echo -ne "d\n$partnum\n"    >> $FDISK_TMP
	fi
    done

    echo "Deleting partition... "
    /sbin/fdisk ${DISK} >/dev/null 2>&1 < $FDISK_TMP
    rm -rf $FDISK_TMP
    echo "done. "
}

__add_partition()
{
    FDISK_TMP2=/tmp/.fdisk2.$$
    DISK=$1
    shift

    num=0
    block=1

    while [ $1 ]
    do
	num=$((num+1))

	end=$((block+$1-1))
	type=$2

	if [ $num -eq 1 ]; then
	    echo -ne "n\np\n$num\n$block\n$end\nt\n$type\na\n$num\n" >> $FDISK_TMP2
	else
	    echo -ne "n\np\n$num\n$block\n$end\nt\n$num\n$type\n" >> $FDISK_TMP2
	fi

	block=$((block+$1))

	shift
	shift
    done
    echo -ne "w\n" >> $FDISK_TMP2

    echo "Adding partition... "
    /sbin/fdisk ${DISK} >/dev/null 2>&1 < $FDISK_TMP2
    rm -rf $FDISK_TMP2
    echo "done. "
}


DEV=$1

# variables
TOP=/mnt/tmp
IMAGE=$TOP/mnt/source
RUNTIME=$TOP/mnt/runtime
SYSIMAGE=$TOP/mnt/sysimage

MINIMUMONLY="no"


cleanup()
{
    echo "Install aborted. Power off"
    umount $SYSIMAGE/tmp >/dev/null 2>&1
    umount $SYSIMAGE/sys >/dev/null 2>&1
    umount $SYSIMAGE/proc/sys/fs/binfmt_misc >/dev/null 2>&1
    umount $SYSIMAGE/proc >/dev/null 2>&1
    umount $IMAGE >/dev/null 2>&1
    umount $SYSIMAGE >/dev/null 2>&1
    umount $RUNTIME >/dev/null 2>&1
    rm -rf $TOP/* >/dev/null 2>&1
    umount /dev/sr0 >/dev/null 2>&1
    eject /dev/sr0 >/dev/null 2>&1
    sleep 5
    poweroff
}

trap cleanup SIGINT SIGTERM

# Get us a controlling tty
while [ -z "$__HAVE_CTTY" ]; do
    __HAVE_CTTY=true /sbin/getctty /dev/console /init "$@"
done

# to create device file
if [ ! -f /proc/partitions ]; then
    mount -n -t proc none /proc
fi
if [ ! -d /sys/block ]; then
    mount -n -t sysfs none /sys
    /sbin/udevstart
    echo -n "/sbin/udevsend" > /proc/sys/kernel/hotplug
    sleep 15
    /sbin/udevstart
fi

#
PATH=/sbin/:/bin:/usr/sbin:/usr/bin

export PATH

# umount all devices
cd /
umount -a > /dev/null 2>&1
umount /mnt/root > /dev/null 2>&1


# select device
for __dev in `ls /sys/block`
do
    if [ x"${__dev#loop}" != "x${__dev}" -o x"${__dev#ram}" != "x${__dev}" -o x"${__dev#sr}" != "x${__dev}" ]; then
	# skip loopX or ramX or srX
	continue
    fi

    # check disk size
    DISKSIZE=`/sbin/fdisk -l /dev/${__dev} 2> /dev/null | awk '($1 == "Disk") {printf("%d", $5/1024/1024/1024)}'`

    if [ "x${DISKSIZE}" = "x" ]; then
	# No disk
	continue
    fi

    if [ ${DISKSIZE} -lt 1 ]; then
	continue
    fi

    __dev_list="$__dev_list $__dev"
done

while : ; do
    line=1
    echo ""
    echo "Starting PS3 Linux installer"
    for __dev in ${__dev_list}
    do
	echo "${line}) $__dev"
	line=$((line+1))
    done
    echo -n "Select device to install? "
    read answer
    if [ $answer -lt 1 -o $answer -ge $line ]; then
	echo "answer = $answer, line = $line"
	echo 'Invalid selection.'
    else
	DEV=`echo $__dev_list | cut -f $answer -d' '`
        DEV="/dev/$DEV"
	break
    fi
done

if [ -z ${DEV} ]; then
    DEV="/dev/ps3da"
fi

if [ "${DEV}" != "/dev/ps3da" ]; then
    if [ ${DEV%%[0-9]*} != ${DEV} ]; then
    	echo "install-fc diskname"
	cleanup
        exit 1
    fi
    LABEL=${DEV#/dev/}
else
    LABEL="/"
fi

if [ ! -b ${DEV} ]; then
    echo "${DEV} is not found. Waiting 10 seconds."
    sleep 10
    if [ ! -b ${DEV} ]; then
    	echo "Unknown disk ${DEV}"
	cleanup
    	exit 1
    fi
fi

# check disk size
DISKSIZE=`/sbin/fdisk -l $DEV 2> /dev/null | awk '($1 == "Disk") {printf("%d", $5/1024/1024/1024)}'`

if [ ${DISKSIZE} -lt 9 ]; then
    MINIMUMONLY="yes"
fi

# set cylinder num
CYL=`/sbin/fdisk -l $DEV 2> /dev/null | awk '($2 == "heads,") {print $5}'`

# set unit size
UNITSIZE=`/sbin/fdisk -l $DEV 2> /dev/null | awk '($1 == "Units") {print $9}'`

if [ ${UNITSIZE} -eq 0 ]; then
    echo "Illegal unitsize"
    cleanup
    exit 1
fi

PART2=$((512 * 1024 * 1024 / $UNITSIZE))
PART1=$(($CYL - $PART2))

# disable screen saver
/bin/setterm -blank 0

# get GAMETIME
GAMETIME=`/sbin/ps3-flash-util -s 2> /dev/null | grep 'p\.rtc_diff' | grep -o '[0-9]*$' `
RETVAL=$?
if [ $RETVAL -ne 0 ]; then
    echo "Can not set clock value"
    cleanup
    exit 1
fi

# add GAMETIME entry to the database
/sbin/ps3-flash-util -D 2 1 ${GAMETIME} 2> /dev/null
RETVAL=$?
if [ $RETVAL -ne 0 ]; then
    # Format flash database
    /sbin/ps3-flash-util -F 2> /dev/null
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        echo "Can not format flash database"
        cleanup
        exit 1
    fi
    /sbin/ps3-flash-util -D 2 1 ${GAMETIME} 2> /dev/null
    if [ $RETVAL -ne 0 ]; then
        echo "Can not set clock value"
        cleanup
        exit 1
    fi
fi

/sbin/hwclock -s
RETVAL=$?
if [ $RETVAL -ne 0 ]; then
    echo "Can not set hwclock"
    cleanup
    exit 1
fi

# create directory
rm -rf $TOP
mkdir -p $IMAGE $RUNTIME $SYSIMAGE
cd $TOP
mkdir proc sys tmp dev etc bin

# Eject media
umount /dev/sr0 >/dev/null 2>&1
eject /dev/sr0 >/dev/null 2>&1

# Mount Fedora Core install DVD
echo "Please insert Fedore Core install DVD."
echo -n "Is it OK? (y/n): "

read answer
if [ "$answer" != "y" ]; then
    cleanup
    exit 1
fi

if ! mount -o ro /dev/sr0 $IMAGE; then
    echo "Fedora Core install DVD mount failed"
    cleanup
    exit 1
fi

if [ -f $IMAGE/.discinfo ]; then
    if ! grep -q "Fedora Core" $IMAGE/.discinfo ||
       ! grep -q "ppc" $IMAGE/.discinfo ; then
    	echo "Not Fedora Core install DVD"
    	cleanup
    	exit 1
    fi
else
    echo "Not Fedora Core install DVD"
    cleanup
    exit 1
fi

FEDORA=`grep "Fedora Core" $IMAGE/.discinfo`

case "$FEDORA" in
  "Fedora Core 6")
    echo -n "Initializing install environment..."
    cp $IMAGE/images/stage2.img /tmp
    FC="fc6"
    echo "done.";;
  *)
    echo "Not Fedora Core install DVD"
    cleanup
    exit 1;;
esac

if ! mount -t squashfs -o ro,loop /tmp/stage2.img $RUNTIME; then
    echo "$FEDORA installer runtime mount failed"
    cleanup
    exit 1
fi
	

# Create install Environment
cd $TOP
ln -s /mnt/runtime/lib lib 
ln -s /mnt/runtime/usr usr

touch $TOP/etc/mtab

mkdir -p $TOP/etc/rpm
mkdir -p $TOP/var/lib/rpm
echo "%_transaction_color   3" 	> $TOP/etc/rpm/macros
echo "ppc64-redhat-linux" 	> $TOP/etc/rpm/platform

# select install system
while : ; do
    echo "1) $FEDORA minimum install"
    if [ "$MINIMUMONLY" = "no" ]; then
        echo "2) $FEDORA full install"
    fi
    echo -n "Select install system? "
    read answer
    if [ "$answer" = "1" ]; then
	selection="${FC}-minimum"
	break
    elif [ "$answer" = "2" -a "$MINIMUMONLY" = "no" ]; then
	selection="${FC}-full"
	break
    else
	echo 'Invalid selection.'
    fi
done

# delete all partitions
echo "Caution!!. All data in $DEV are removed."
echo -n "Is it OK? (y/n): "

read answer

if [ "$answer" != "y" ]; then
    echo "Install aborted."
    cleanup
    exit 1
fi


# Delete All partitions
__delete_all_partition $DEV

# sdX1 Total size - 512MB Linux, sdX2 512MB swap
__add_partition $DEV $PART1 83 $PART2 82

# To create device file
/sbin/udevstart

# cpu device files
cp -a /dev/* $TOP/dev

# initialize HD
echo "Initializing ${DEV}1 linux partition... "
if ! mke2fs -q -j -L ${LABEL}1 ${DEV}1; then
    echo "mke2fs ${DEV}1 failed"
    cleanup
    exit 1
fi

# create swap
if ! chroot $TOP mkswap -L SWAP-${DEV#/dev/}2 ${DEV}2; then
    echo "mkswap ${DEV}2 failed"
    cleanup
    exit 1
fi
echo "done."

# mount HD
if ! mount -t ext3 ${DEV}1 $SYSIMAGE; then
    echo "mount ${DEV}1 failed"
    cleanup
    exit 1
fi

# swapon
chroot $TOP /usr/bin/swapon ${DEV}2

# create minimum directories on HD
mkdir -p $SYSIMAGE/proc
mkdir -p $SYSIMAGE/sys
mkdir -p $SYSIMAGE/tmp
mkdir -p $SYSIMAGE/dev
mkdir -p $SYSIMAGE/etc
mkdir -p $SYSIMAGE/etc/sysconfig
mkdir -p $SYSIMAGE/etc/sysconfig/network-scripts
mkdir -p $SYSIMAGE/etc/udev/makedev.d/
mkdir -p $SYSIMAGE/var/lib/rpm

# copy device files
cp -a /dev/* $SYSIMAGE/dev

# mount 
mount -t proc none $SYSIMAGE/proc
mount -t binfmt_misc none $SYSIMAGE/proc/sys/fs/binfmt_misc
mount -t sysfs none $SYSIMAGE/sys
mount -t ramfs none $SYSIMAGE/tmp

# create etc/fstab
cat > $SYSIMAGE/etc/fstab << EOF
LABEL=${LABEL}1         /                       ext3    defaults        1 1
/dev/devpts             /dev/pts                devpts  gid=5,mode=620  0 0
/dev/shm                /dev/shm                tmpfs   defaults        0 0
none                    /spu                    spufs   defaults        0 0
/dev/proc               /proc                   proc    defaults        0 0
/dev/sys                /sys                    sysfs   defaults        0 0
LABEL=SWAP-${DEV#/dev/}2    swap                    swap    defaults        0 0
/dev/cdrom		/mnt/cdrom		auto	noauto		0 0
EOF


# keyboard
echo 'KEYTABLE="us"' > $SYSIMAGE/etc/sysconfig/keyboard

# i18n
cat > $SYSIMAGE/etc/sysconfig/i18n << EOF
LANG="en_US.UTF-8"
SYSFONT="latarcyrheb-sun16"
EOF

# udev
cat > $SYSIMAGE/etc/udev/makedev.d/45-ps3pf.nodes << EOF
hvc0
pmu
EOF

# network
cat > $SYSIMAGE/etc/sysconfig/network << EOF
NETWORKING=yes
HOSTNAME=localhost.localdomain
EOF

cp /etc/ifcfg-eth0 $SYSIMAGE/etc/sysconfig/network-scripts/ifcfg-eth0
cp /etc/ifcfg-eth1 $SYSIMAGE/etc/sysconfig/network-scripts/ifcfg-eth1

cat > $SYSIMAGE/etc/resolv.conf << EOF
EOF

cat > $SYSIMAGE/etc/hosts << EOF
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1	localhost.localdomain localhost
EOF


# authconfig
cat > $SYSIMAGE/etc/sysconfig/authconfig << EOF
USEWINBINDAUTH=no
USEHESIOD=no
USESYSNETAUTH=no
USEKERBEROS=no
USESHADOW=yes
USESMBAUTH=no
USELDAPAUTH=no
USELOCAUTHORIZE=no
USEWINBIND=no
USEDB=no
USEPASSWDQC=no
USEMD5=yes
USELDAP=no
USECRACKLIB=yes
USENIS=no
EOF


# Initialize rpm db
/usr/sbin/chroot $TOP rpm --root /mnt/sysimage --initdb

# copy files for RPM install
cp /usr/share/fc6-full.txt $TOP/etc/rpm
cp /usr/share/fc6-minimum.txt $TOP/etc/rpm
cp /sbin/install-rpm $TOP/bin/install-rpm

# Execute rpm
if [ "${selection}" = "${FC}-minimum" ]; then
    echo "Installing ${FEDORA} RPMs. "
else
    echo "Installing ${FEDORA} RPMs. Please wait about two hour."
fi
/usr/sbin/chroot $TOP /bin/install-rpm ${selection}

# Remove old RPMs
case "${FC}" in
    fc6)
	KHED=`/usr/sbin/chroot $TOP rpm -qa --root /mnt/sysimage kernel-headers | grep kernel-headers`
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
	    /usr/sbin/chroot $TOP rpm -e --nodeps --root /mnt/sysimage kernel-headers-2.6.18-1.2798.fc6.ppc64 kernel-headers-2.6.18-1.2798.fc6.ppc
	fi;;
esac

KER=`/usr/sbin/chroot $TOP rpm -qa --root /mnt/sysimage kernel | grep kernel`
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
    /usr/sbin/chroot $TOP rpm -e --nodeps --root /mnt/sysimage kernel
fi

WPA_S=`/usr/sbin/chroot $TOP rpm -qa --root /mnt/sysimage wpa_supplicant | grep wpa_supplicant `
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
    /usr/sbin/chroot $TOP rpm -e --nodeps --root /mnt/sysimage wpa_supplicant
fi

# umount 
umount $SYSIMAGE/tmp
umount $SYSIMAGE/sys
umount $SYSIMAGE/proc/sys/fs/binfmt_misc
umount $SYSIMAGE/proc


# Eject Fedora Core install DVD
umount /dev/sr0
eject /dev/sr0

# for debug
# cat /proc/mounts

# check Fedora Core install
RPMNUM=`/usr/sbin/chroot $TOP rpm -qa --root /mnt/sysimage | /usr/sbin/chroot $TOP wc -l `
if [ $RPMNUM -eq 0 ]; then
    echo "Fedora Core install failed."
    cleanup
    exit 1
fi

# mount CL install DVD
while : ; do
    echo "Please insert PS3 Linux Distributor's Starter Kit CD."
    echo -n "Is it OK? (y/n): "

    read answer
    if [ "$answer" = "n" ]; then
	cleanup
    	exit 1
    fi

    if [ "$answer" != "y" ]; then
	echo ""
	continue
    fi

    if mount -o ro /dev/sr0 $IMAGE; then
	if [ -f $IMAGE/etc/kboot.conf ]; then
	    break
	fi
	umount $IMAGE
	echo "Not PS3 Linux Distributor's Starter Kit CD."
    fi
done


# mount 
mount -t proc none $SYSIMAGE/proc
mount -t binfmt_misc none $SYSIMAGE/proc/sys/fs/binfmt_misc
mount -t sysfs none $SYSIMAGE/sys
mount -t ramfs none $SYSIMAGE/tmp

# install target binary
echo -n "Installing target binary..."
if ! chroot $TOP rpm -ivh --nodeps --root /mnt/sysimage /mnt/source/target/*.rpm; then
    echo "Target package install failed"
    cleanup
    exit 1
fi

if [ -d $IMAGE/target/snapshot ]; then
    if ! chroot $TOP rpm -ivh --nodeps --root /mnt/sysimage /mnt/source/target/snapshot/*.rpm; then
    	echo "Target package install failed"
    	cleanup
    	exit 1
    fi
fi

# service settings
case "${FC}" in
    fc6)
	SERVICES="bluetooth cpuspeed arptables_jf hidd iptables ip6tables isdn iscsi auditd irqbalance nfslock mcstrans pcscd restorecond mdmonitor rpcidmapd rpcgssd autofs smartd hplip iprinit iprupdate iprdump cups sendmail xfs atd avahi-daemon cups-config-daemon"
	for s in $SERVICES
	do
	    if [ -f $SYSIMAGE/etc/init.d/$s ]; then
	    	chroot $SYSIMAGE /sbin/chkconfig --level 35 $s off
	    fi
	done;;
esac

# umount 
umount $SYSIMAGE/tmp
umount $SYSIMAGE/sys
umount $SYSIMAGE/proc/sys/fs/binfmt_misc
umount $SYSIMAGE/proc

chroot $TOP chmod 1777 /mnt/sysimage/tmp

# install initrd
if ! cp $IMAGE/target/initrd.img* $SYSIMAGE/boot; then
    echo "Initrd copy failed"
    cleanup
    exit 1
fi

if [ -d $IMAGE/target/snapshot ]; then
    if ! cp $IMAGE/target/snapshot/initrd.img* $SYSIMAGE/boot; then
    	echo "Initrd copy failed"
    	cleanup
    	exit 1
    fi
fi

umount $IMAGE


mkdir -p $SYSIMAGE/mnt/cdrom
mkdir -p $SYSIMAGE/spu

# create kboot.conf
cat > $SYSIMAGE/etc/kboot.conf << EOF
default=linux
timeout=10
root=LABEL=${LABEL}1
EOF

KERNELVER=`chroot $TOP rpm --root /mnt/sysimage -q --queryformat "%{VERSION} " kernel`
CMDLINE=`cat /proc/cmdline`

# remove "root=" in $CMDLINE
args=
for arg in $CMDLINE
do
    if [ "x${arg#root=}" = "x$arg" ]; then
	args="$args $arg"
    fi
done

CMDLINE="$args"

for kver in $KERNELVER
do
    if [ "$kver" = "2.6.24" ]; then
	label=""
    else
	label=${kver##2.6.}
    fi
    cat >> $SYSIMAGE/etc/kboot.conf << EOF
safe='/boot/vmlinux-$kver initrd=/boot/initrd.img-$kver video=safe'
linux$label='/boot/vmlinux-$kver initrd=/boot/initrd.img-$kver '
EOF
done

# clock settings
cat > $SYSIMAGE/etc/sysconfig/clock << EOF
ZONE="Asia/Tokyo"
UTC=true
ARC=false
EOF

cp $SYSIMAGE/usr/share/zoneinfo/Japan $SYSIMAGE/etc/localtime


# ps3pf.modules
cat > $SYSIMAGE/etc/sysconfig/modules/ps3.modules << EOF
#!/bin/sh
for i in snd_ps3;do
  modprobe \$i >/dev/null 2>&1
done
EOF

chroot $TOP chmod 755 /mnt/sysimage/etc/sysconfig/modules/ps3.modules

# sound
mkdir -p $SYSIMAGE/etc/alsa/cards/
cp /etc/PS3.conf $SYSIMAGE/etc/alsa/cards/

# rpm settings
echo "ppc64-redhat-linux" > $SYSIMAGE/etc/rpm/platform
echo "%_transaction_color   3" > $SYSIMAGE/etc/rpm/macros


# modprobe.conf
cat > $SYSIMAGE/etc/modprobe.conf << EOF
alias scsi_hostadapter ps3disk
alias scsi_hostadapter1 ps3rom
alias scsi_hostadapter2 ps3flash
alias usb-controller ehci-hcd
alias usb-controller1 ohci-hcd
EOF

# shadow
chroot $SYSIMAGE /usr/sbin/pwconv

# root passwd
chroot $SYSIMAGE /usr/bin/passwd root


# X settings
cp /etc/xorg.conf-vfb	$SYSIMAGE/etc/X11
cp /etc/xorg.conf-vfb	$SYSIMAGE/etc/X11/xorg.conf
cp /etc/kudzu	   	$SYSIMAGE/etc/init.d

if [ "${selection}" = "fc6-full" ]; then
    chroot $SYSIMAGE /usr/bin/gtk-update-icon-cache -f /usr/share/icons/hicolor/
fi

# misc settings
cp -r $SYSIMAGE/etc/skel/./ $SYSIMAGE/root/

cat $SYSIMAGE/etc/init.d/halt \
 | chroot $TOP sed 's!/sbin/kexec!/usr/sbin/kexec!' \
 | chroot $TOP sed 's!$kexec_command -e!taskset 1 $kexec_command -e!' \
 > $SYSIMAGE/etc/init.d/halt.modified
cat $SYSIMAGE/etc/init.d/halt.modified > $SYSIMAGE/etc/init.d/halt
rm $SYSIMAGE/etc/init.d/halt.modified

cat $SYSIMAGE/etc/yum.conf | awk \
	'//;
	/^$/ && !F {
		print "# exclude PS3 specific packages\nexclude=kernel-* glibc-kernheaders-* kernel-headers-* kexec-tools-*\n";
		F=1
	}' > $SYSIMAGE/etc/yum.conf.modified
cat $SYSIMAGE/etc/yum.conf.modified > $SYSIMAGE/etc/yum.conf
rm $SYSIMAGE/etc/yum.conf.modified


# swapoff
chroot $TOP /usr/bin/swapoff ${DEV}2

# eject DVD
eject /dev/sr0

# unmount disk and cdrom
umount $SYSIMAGE/tmp >/dev/null 2>&1
umount $SYSIMAGE/sys >/dev/null 2>&1
umount $SYSIMAGE/proc/sys/fs/binfmt_misc >/dev/null 2>&1
umount $SYSIMAGE/proc >/dev/null 2>&1
umount $IMAGE >/dev/null 2>&1
umount $SYSIMAGE >/dev/null 2>&1
umount $RUNTIME >/dev/null 2>&1
rm -rf $TOP/* >/dev/null 2>&1

# 

# Ending
echo "Install done."
echo -n "Please type any key to restart : "
read answer
reboot
