#!/usr/bin/bash

#
# Author : mishuang
# URL : http://blogold.chinaunix.net/u/23177/showart_2182517.html
# Updated by Hugues Lepesant
#

LOFIADM=/usr/sbin/lofiadm
AWK=/usr/gnu/bin/awk
GSED=/usr/bin/gsed

UMOUNT=/usr/sbin/umount
MOUNT=/usr/sbin/mount

GREP=/usr/gnu/bin/grep
GZIP=/usr/bin/gzip
MKDIR=/usr/gnu/bin/mkdir
FIND=/usr/gnu/bin/find
CPIO=/usr/bin/cpio
MKISOFS=/usr/bin/mkisofs

ISO_FILE="/export/home/hugues/iso/osol-dev-134-x86.iso"
ISO_NEW_FILE=$(printf "%s/%s" $(dirname ${ISO_FILE}) "osol-dev-134-x86_custom.iso")

ISO_MNT_DIR="/mnt/osol"
ISO_TMP_DIR="/var/tmp/osol"

BA_MNT_DIR="/mnt/boot_archive"
BA_FILE="/var/tmp/boot_archive"

CP='/bin/cp -f'
RM='/bin/rm -rf'

function clear_lofi
{
    lofis=$(${LOFIADM} | ${AWK} '/\/dev\/lofi/{print $1}')

    for lofi in ${lofis}
    do
        ${LOFIADM} -d ${lofi}
    done
}

function set_kbd_lang
{
    ${GSED} -i -e 's/kbd -s/& US-English/' -e 's/set_lang/& default/' $1/lib/svc/method/media-fs-root
}

function create_x86_iso
{
    ${UMOUNT} ${ISO_MNT_DIR}
    ${UMOUNT} ${BA_MNT_DIR}

    clear_lofi

    ${RM} ${ISO_TMP_DIR} ${BA_FILE}
    ${RM} ${ISO_NEW_FILE}

    ${MKDIR} -p ${ISO_MNT_DIR} ${ISO_TMP_DIR} ${BA_MNT_DIR}

    iso_lofi=$(${LOFIADM} -a ${ISO_FILE})
    ${MOUNT} -F hsfs ${iso_lofi} ${ISO_MNT_DIR}

    cd ${ISO_MNT_DIR}

    ${FIND} . -depth -print | ${CPIO} -pdum ${ISO_TMP_DIR}
    cd -

    for dir in "" "amd64"
    do
        ${GZIP} -cd ${ISO_TMP_DIR}/platform/i86pc/${dir}/boot_archive > ${BA_FILE}

        ba_lofi=$(${LOFIADM} -a ${BA_FILE})
        sleep 5
        ${MOUNT} ${ba_lofi} ${BA_MNT_DIR}

        ${CP} /export/home/hugues/2.00.15_Solaris_MegaCLI.zip ${BA_MNT_DIR}/root
        ${CP} /export/home/hugues/postinstall.sh ${BA_MNT_DIR}/root

        set_kbd_lang ${BA_MNT_DIR}

        sleep 5
        ${UMOUNT} ${BA_MNT_DIR}
        ${GZIP} -c ${BA_FILE} > ${ISO_TMP_DIR}/platform/i86pc/${dir}/boot_archive
        sleep 5
        ${LOFIADM} -d ${ba_lofi}
    done

    ${MKISOFS} -o ${ISO_NEW_FILE}    \
        -b boot/grub/stage2_eltorito \
        -c .catalog                  \
        -no-emul-boot                \
        -boot-load-size 4            \
        -boot-info-table             \
        -N -l -R -U -allow-multidot  \
        -no-iso-translate            \
        -cache-inodes -d -D          \
        -V "OpenSolaris"             \
        ${ISO_TMP_DIR}

    ${UMOUNT} ${ISO_MNT_DIR}
    ${LOFIADM} -d ${iso_lofi}
    ${RM} ${ISO_TMP_DIR} ${BA_FILE}
}

create_x86_iso
