#!/bin/bash
#================
# FILE          : preinit
#----------------
# PROJECT       : openSUSE KIWI Image System
# COPYRIGHT     : (c) 2006 SUSE LINUX Products GmbH. All rights reserved
#               :
# AUTHOR        : Marcus Schaefer <ms@suse.de>
#               :
# BELONGS TO    : Operating System images
#               :
# DESCRIPTION   : This file is called after the image root
#               : has changed by the linuxrc script
#               :
# STATUS        : BETA
#----------------


# Changes from kiwi upstream:
#
# do not call kernelCheck
# fixed setupInitrd to handle multiple kernel versions with dracut
#

#======================================
# Functions
#--------------------------------------
. /include

#======================================
# setupInitrd - forked from  /include
#--------------------------------------
function setupInitrd {
    # /.../
    # call mkinitrd to create the distro initrd
    # ----
    local IFS=$IFS_ORIG
    bootLoaderOK=1
    local umountProc=0
    local umountSys=0
    local systemMap=0
    local dracutExec=$(lookup dracut 2>/dev/null)
    local mkinitrdExec=$(lookup mkinitrd 2>/dev/null)
    local params
    local running
    local rlinux
    local rinitrd
    local kernel_version
    for i in $(find /boot/ -name "System.map*");do
        systemMap=1
    done
    setupDefaultTheme
    if [ $systemMap -eq 1 ];then
        #======================================
        # Cleanup
        #--------------------------------------
        rm -f /boot/initrd-*.img
        #======================================
        # Prepare for tool call
        #--------------------------------------
        if [ ! -e /proc/mounts ];then
            mount -t proc proc /proc
            umountProc=1
        fi
        if [ ! -e /sys/block ];then
            mount -t sysfs sysfs /sys
            umountSys=1
        fi
        modprobe dm-mod &>/dev/null
        updateModuleDependencies
        #======================================
        # Call initrd creation tool
        #--------------------------------------
        if [ -x "$dracutExec" ]; then
            # 1. dracut
            for i in /lib/modules/*;do
                if [ ! -d $i ];then
                    continue
                fi
                kernel_version=${i##*/}
                params=" -f /boot/initrd-$kernel_version $kernel_version"
                Echo "Creating dracut based initrd for $kernel_version"
                if ! $dracutExec -H $params;then
                    Echo "Can't create initrd with dracut"
                    systemIntegrity=unknown
                    bootLoaderOK=0
                fi
            done
        elif [ -x "$mkinitrdExec" ]; then
            # 2. mkinitrd
            Echo "Creating mkinitrd based initrd"
            if grep -qi param_B $mkinitrdExec;then
                params="-B"
            fi
            if ! $mkinitrdExec $params;then
                Echo "Can't create initrd with mkinitrd"
                systemIntegrity=unknown
                bootLoaderOK=0
            fi
        else
            # no tool found
            Echo "Coudn't find a tool to create initrd image"
            systemIntegrity=unknown
            bootLoaderOK=0
        fi
        #======================================
        # Cleanup kiwi firstboot initrd
        #--------------------------------------
        if [ $bootLoaderOK = "1" ];then
            if [ -f /boot/initrd.vmx ];then
                rm -f /boot/initrd.vmx
            fi
            if [ -f /boot/linux.vmx ];then
                rm -f /boot/linux.vmx
            fi
            if [ -f /boot/initrd.uboot ];then
                rm -f /boot/initrd.uboot
            fi
        fi
        #======================================
        # Loader exceptions
        #--------------------------------------
        if [ "$loader" = "syslinux" ];then
            # /.../
            # if syslinux is used we need to make sure to copy
            # the kernel and initrd to /boot on the boot partition.
            # This is normally done by the boot -> . link but we
            # can't create links on fat
            # ----
            IFS="," ; for i in $KERNEL_LIST;do
                if test -z "$i";then
                    continue
                fi
                kernel=`echo $i | cut -f1 -d:`
                initrd=`echo $i | cut -f2 -d:`
                break
            done
            IFS=$IFS_ORIG
            mkdir -p /boot/boot
            cp /boot/$kernel /boot/boot/
            cp /boot/$initrd /boot/boot/
        fi
        #======================================
        # Cleanup mounts
        #--------------------------------------
        rmmod dm-mod &>/dev/null
        if [ $umountSys -eq 1 ];then
            umount /sys
        fi
        if [ $umountProc -eq 1 ];then
            umount /proc
        fi
    else
        Echo "Image doesn't include kernel system map"
        Echo "Can't create initrd"
        systemIntegrity=unknown
        bootLoaderOK=0
    fi
    #======================================
    # Display a warning on failure
    #--------------------------------------
    # Warning message is disabled because sometimes the message
    # can't be displayed on the console which leads to a stopped
    # system but the user has no clue why
    #
    #if [ $bootLoaderOK = 0 ];then
    #    if lookup dialog &>/dev/null;then
    #        Dialog \
    #            --backtitle \"$TEXT_BOOT_SETUP_FAILED\" \
    #            --msgbox "\"$TEXT_BOOT_SETUP_FAILED_INFO\"" 10 70
    #    else
    #        systemException \
    #            "$TEXT_BOOT_SETUP_FAILED\n\n$TEXT_BOOT_SETUP_FAILED_INFO" \
    #        "waitkey"
    #    fi
    #fi
}


#======================================
# 1) start error log
#--------------------------------------
errorLogStart
Echo "Calling pre-init stage in system image"

#======================================
# 2) check for LOCAL_BOOT
#--------------------------------------
if [ $LOCAL_BOOT = "yes" ];then
    exit 0
fi

#======================================
# 3) start udev
#--------------------------------------
mountSystemFilesystems
udevSystemStart

#======================================
# 4) update mount table
#--------------------------------------
updateMTAB

#======================================
# 5) create framebuffer devices
#--------------------------------------
if [ "$systemIntegrity" = "clean" ];then
    createFramebufferDevices
fi

#======================================
# 6) create initrd on diskful
#--------------------------------------
if  [ ! -z "$imageDiskDevice" ]      && \
    [ "$systemIntegrity" = "clean" ] && \
    [ -z "$NETBOOT_ONLY" ]
then
    if [ -z "$UNIONFS_CONFIG" ] && [ -z "$COMBINED_IMAGE" ];then
        #======================================
        # use distro initrd tool
        #--------------------------------------
        setupInitrd
    else
        #======================================
        # use kiwi initrd downloaded before
        #--------------------------------------
        bootLoaderOK=1
    fi
fi

#======================================
# 7) Install boot loader on diskful
#--------------------------------------
if [ "$bootLoaderOK" = 1 ] && [ -z "$DO_NOT_INSTALL_BOOTLOADER" ]; then
    installBootLoader
fi

#======================================
# 8) check for valid mount points
#--------------------------------------
if [ ! -z "$imageDiskDevice" ] && [ "$systemIntegrity" = "clean" ];then
    for i in $(echo $PART_MOUNT | tr ':' ' ');do
    if [ ! -z "$i" ] && [ ! -e "$i" ] && [ ! "$i" = "x" ];then
        mkdir -p $i
    fi
    done
fi

#======================================
# 9) Update /etc/ImageVersion files
#--------------------------------------
if [ ! -z "$imageDiskDevice" ] && [ "$systemIntegrity" = "clean" ];then
    count=0
    for i in $(echo $IMAGE | tr , ' ');do
        count=$(($count + 1))
        field=0
        for n in $(echo $i | tr ';' ' ');do
        case $field in
            0) field=1 ;;
            1) imageName=$n   ; field=2 ;;
            2) imageVersion=$n; field=3
        esac
        done
        atversion="$imageName-$imageVersion"
        versionFile="/etc/ImageVersion-$atversion"
        md5sum=`getSystemMD5Status $count`
        if test `getSystemIntegrity $count` = "clean";then
            echo "$atversion $md5sum" > $versionFile
        fi
    done
fi

#======================================
# 10) setup console
#--------------------------------------
if [ "$systemIntegrity" = "clean" ];then
    setupConsole
    setupMachineID
fi

#======================================
# 11) kernelCheck
#--------------------------------------
# kernelCheck # conflicts with kernel check in saltboot

#======================================
# 12) Run user script
#--------------------------------------
runHook preCallInit

#======================================
# 13) kill udev
#--------------------------------------
udevSystemStop
umountSystemFilesystems
