#!/bin/sh
# -fu
#
# Copyright (C) 2007  Andrew V. Stepanov <stanv@altlinux.org>
#
# Get Every Archive from git package Repository.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#


# Notes XXX:
#   * Assume that all device drivers (modules) already loaded
#   (not need do modprobe, or init LVM, raid, or anything else)
#   * Using /proc to see mounted devices
#   * Suppose /dev already mounted
#   * Parse /proc/cmdline for string "live_rw"

# _________
# Variables
# ~~~~~~~~~
PROG="${0##*/}"
PROG_VERSION='1.0.0'

. /etc/init.d/functions

. gettext.sh

TEXTDOMAIN=remount_rw
TEXTDOMAINDIR='/usr/share/locale'
export TEXTDOMAINDIR TEXTDOMAIN

SYS_DISKS=
DIALOG="dialog"
FS_LABEL="alt_rw_root"
rwroot="/mnt/root/"
backtitle="ALT Linux Live"
supported_fs="xfs ext2 ext3 reiserfs vfat ntfs iso9660 nfs nfs4 smbfs"
saved_sessions=()
dirs="var etc lib bin usr sbin home root media boot" # no tmp dev


# Show dialog widgets into STDERR

# _________
# Functions
# ~~~~~~~~~

msg_info()
{
    printf '%s\n' "$PROG: $*" >&2
}

fatal()
{
    msg_info "$@"
    exit 1
}

exit_handler()
{
    local rc=$?
    trap - EXIT

    local item=
    for item in $dirs; do
        [ -d "${rwroot}/${item}" ] || mkdir -p "${rwroot}/${item}"
        mount -n -t aufs -o "remount,prepend=${rwroot}/${item}=rw" none "/$item" ||
            fatal "FAIL: mount -n -t aufs -o remount,prepend=${rwroot}/${item}=rw none /$item"
    done

    exit $rc
}

dialog_quit()
{
    $DIALOG --clear --output-fd 3 3>&1 1>&2
    $DIALOG --output-fd 3 --pause "$(gettext "Continue booting using RAM for temporary files. . .")" 20 75 3 3>&1 1>&2
}

dialog_greeting()
{
    local menu= choice= title= ret=

    title="\"$(gettext "Boot options:")\""

    [ "${#saved_sessions[*]}" -ne "0" ] && menu="$menu \"restore\" \"$(gettext "Continue Saved Session")\""
    menu="$menu \"init\" \"$(gettext "Use R/W Device for modified files")\""
    menu="$menu \"quit\" \"$(gettext "Continue Booting using RAM")\""

    $DIALOG --clear --output-fd 3 3>&1 1>&2
    choice="$(eval $DIALOG --nocancel --backtitle "\"$backtitle\"" --output-fd 3 --menu "$title" 20 75 15 "$menu" 3>&1 1>&2)"
    ret="$?"
    echo "$choice"
    return $ret
}

get_var()
{
    local var= from=
    var="$1" && shift
    from="$1"
    echo "$from" | grep "$var" | sed -n "s/.*${var}=//p"
}

is_supported_fs()
{
    local ID_FS_TYPE="$1" && shift
    [ -z "$ID_FS_TYPE" ] && return 1
    [ "$ID_FS_TYPE" != "$(echo $supported_fs | grep -o "$ID_FS_TYPE" 2>/dev/null)" ] && return 1
    return 0
}

is_device_mounted()
{
    local dev="$1" && shift
    [ -z "$dev" ] && return 1
    [ -f "/proc/mounts" ] || return 1
    # find mount point
    [ -n "$(cat "/proc/mounts" | grep "$dev " | cut -d ' ' -f 2 2>/dev/null)" ] && return 0
    [ -n "$(mount | grep "$dev " | cut -d ' ' -f 3 2>/dev/null)" ] && return 0
    return 1
}

# mount device 
mount_partition()
{
    local dev="$1" && shift
    local udev_info=
    local ID_FS_TYPE=

    udev_info=$(udevadm info --query=all --name="$dev" 2>/dev/null)

    if [ -z "$udev_info" ]; then
        msg="$(printf "$(gettext "Can't get partition info for %s.")" "$dev")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2
        return 1
    fi

    ID_FS_TYPE=$(get_var "ID_FS_TYPE" "$udev_info")

    if [ -z "$ID_FS_TYPE" ]; then
        msg="$(printf "$(gettext "Unknown partition. Does %s have file system?")" "$dev")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2
        return 1
    fi

    if ! is_supported_fs "$ID_FS_TYPE"; then
        msg="$(printf "$(gettext "Unknown filesystem on %s.")" "$dev")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox  "$msg" 20 75 3>&1 1>&2
        return 1
    fi

    # check already mounted
    local mount_dir="/mnt/$dev"

    if is_device_mounted "$dev"; then
        msg="$(printf "$(gettext "%s already mounted. Can't use them.")" "$dev")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2
        return 1
    fi

    # not mounted, mount byself
    [ -d "$mount_dir" ] || mkdir -p "$mount_dir"

    # XXX (ALT Linux not only russian distro!)
    MOUNT_OPTIONS_VFAT="rw,noexec,codepage=866,iocharset=utf8,gid=100,fmask=111,dmask=000"
    MOUNT_OPTIONS_NTFS3G="rw,noexec,locale=ru_RU.utf8,gid=100,fmask=111,dmask=000"   # force
    MOUNT_OPTIONS_OTHER="defaults"
    
    case "$ID_FS_TYPE" in
        "vfat")
              mnt_options="$MOUNT_OPTIONS_VFAT"
              ;;
        "ntfs")
              if which ntfs-3g >/dev/null 2>&1; then
                  ID_FS_TYPE="ntfs-3g"
                  mnt_options="$MOUNT_OPTIONS_NTFS3G"
              else
                  msg="$(printf "$(gettext "Can't mount ntfs parition (%s) in R/W mode.")" "$dev")"
                  $DIALOG --clear --output-fd 3 3>&1 1>&2
                  $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2
                  return 1
              fi
              ;;
        *)
              mnt_options="$MOUNT_OPTIONS_OTHER"
    esac

    if ! mount -o "$mnt_options" -t "$ID_FS_TYPE" "/dev/$dev" "$mount_dir" >/dev/null 2>&1; then
        msg="$(printf "$(gettext "Can't mount %s to %s.")" "$dev" "$mount_dir")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2
        return 1
    fi
# info: need umount
    return 0
}

# select and mount loop file
mount_loop_file()
{
    # mnt_dir - point to mounted partition (global variable)
    local loop_file="$1" && shift

    msg="$(printf "$(gettext "Info: %s")" "$(file $loop_file 2>/dev/null)")"
    $DIALOG --clear --output-fd 3 3>&1 1>&2
    $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2

    [ -d "$rwroot" ] || mkdir -p "$rwroot"

    if ! mount -n -o loop -t ext3 "$loop_file" "$rwroot" >/dev/null 2>&1; then
        msg="$(printf "$(gettext "Can't mount %s. Do you sure that is File System?")" "$loop_file")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$msg" 20 75 3>&1 1>&2
        return 1
    fi

    # loop file mounted

    return 0
}

dev_info()
{
    local dev= udev_info= ID_TYPE= ID_VENDOR= ID_MODEL= SIZE= ID_FS_TYPE= ID_FS_LABEL= SIZE=
    local minor=

    dev="$1" && shift

    [ -n "$dev" ] || return 1

    udev_info=$(udevadm info --query=all --name=$dev 2>/dev/null)

    ID_VENDOR=$(get_var "ID_VENDOR" "$udev_info")
    ID_MODEL=$(get_var "ID_MODEL" "$udev_info")
    ID_FS_TYPE=$(get_var "ID_FS_TYPE" "$udev_info")
    ID_FS_LABEL=$(get_var "ID_FS_LABEL" "$udev_info")
    ID_TYPE=$(get_var "ID_TYPE" "$udev_info")
    SIZE=$(get_dev_size $dev)


    # Is minor ?
    minor=$(echo $dev | sed -n -e '/[0-9]$/p')
    if [ -n "$minor" -a -n "$ID_FS_TYPE" ]; then
        echo "$ID_FS_TYPE ${SIZE}${ID_FS_LABEL:+" ($ID_FS_LABEL)"}"
        return 0
    elif [ -n "$minor" ]; then
        echo "$(gettext "(unknown partition)") $SIZE"
        return 0
    fi

    # Has ID_FS_TYPE ?
    if [ -n "$ID_FS_TYPE" ]; then
        # Major - whole disk have one file system
        echo "${ID_VENDOR:+"$ID_VENDOR "}${ID_MODEL:+"$ID_MODEL "}${ID_FS_TYPE} $(SIZE)$(ID_FS_LABEL:+" ($ID_FS_LABEL)")"
        return 0
    fi

    if [ "$ID_TYPE" = "cd" ]; then
        local cd_info= cd_volume= cd_no_media= cd_ret=
        # show cd info
        cd_info="$(isoinfo -d -i "/dev/$dev" 2>/dev/null)"
        cd_volume="$(echo "$cd_info" | grep 'Volume id' | sed -e 's/.*: //' | sed 's/"//g')"
        cd_ret="${ID_VENDOR:+"$ID_VENDOR "}${ID_MODEL:-"Stupid CD drive model"}"
        echo "$cd_info" | grep "Unable to open" >/dev/null || cd_no_media="yes"
        if [ -n "$cd_volume" ]; then
            cd_ret="$cd_ret ($cd_volume)"
        elif [ -n "$cd_no_media" ]; then
            cd_ret="$cd_ret $(gettext "(NO DISK)")"
        fi
        echo "$cd_ret"
        return 0
    fi

    echo "${ID_VENDOR:+"$ID_VENDOR "}${ID_MODEL:+"$ID_MODEL "}$SIZE"
}

find_suitable_devices()
{
    local devices= dev= udev_info= ID_FS_TYPE= suitable_devices=
    
    devices="$(udevadm info --export-db | sed -e '\@/block/@!d; /ram/d; /loop/d; /fd[0-9]/d; s/.*\/block\/// ; s/.*\///')"
    
    for dev in $devices; do
        udev_info="$(udevadm info --query=all --name=$dev 2>/dev/null)"

        ID_FS_TYPE="$(get_var "ID_FS_TYPE" "$udev_info")"

        [ -z "$ID_FS_TYPE" ] && continue # ignore device without filesystems..

        is_supported_fs "$ID_FS_TYPE" || continue

        is_device_mounted "$dev" && continue

        suitable_devices="$suitable_devices $dev"
    done
    
    echo "$suitable_devices"
}

select_dev()
{
    local devices= dev= menu= choice= ret=
    devices="$(find_suitable_devices)"
    if [ -z "$devices" ]; then
        $DIALOG --output-fd 3 --msgbox "$(gettext "Can't find any not mounted devices with known FS type.")" 20 75 3>&1 1>&2
        return 1 # Cancel imitation
    fi
    for dev in $devices; do
        menu="$menu \"${dev}\" \"$(dev_info $dev)\""
    done
    msg="$(gettext "Select device:")"
    choice="$(eval $DIALOG --output-fd 3 --cancel-label Back --backtitle "\"$backtitle\"" --menu "\"$msg\"" 20 75 15 "$menu" 3>&1 1>&2)"
    ret="$?"

    echo $choice

    return "$ret"
}

print_session_name()
{
    local session="$1" && shift
    [ -z "$session" ] && return 1
    
    echo "$session" | sed 's/ (.\+)$//'
    return 0
}

print_session_device()
{
    local session="$1" && shift
    [ -z "$session" ] && return 1

    echo "$session" | sed 's/^.*(\(.\+\))$/\1/'
    return 0
}

select_saved_session()
{
    local session= session_name= session_device= ret= menu= choice= index=0

    if [ "${#saved_sessions[*]}" -eq "1" ]; then
        session=${saved_sessions[0]}
        session_name="$(print_session_name "$session")"
        session_device="$(print_session_device "$session")"
        msg="$(printf "$(gettext "Found saved session %s on %s. Do you wish use it?")" "$session_name" "$session_device")"
        $DIALOG --output-fd 3 --yesno "$msg" 20 75 3>&1 1>&2
        ret="$?"
        [ "$ret" = "0" ] && echo "$session"
        return "$ret"
    fi

    while [ "${#saved_sessions[*]}" -gt "$index" ]; do
        menu="$menu $index \"${saved_sessions[$index]}\""
        index=$((index+1))
    done

    msg="$(gettext "Select saved session:")"
    choice="$(eval $DIALOG --output-fd 3 --cancel-label Back --backtitle "\"$backtitle\"" --menu "\"$msg\"" 20 75 15 "$menu" 3>&1 1>&2)"
    ret="$?"

    [ -n "$choice" ] && echo "${saved_sessions[${choice}]}"

    return "$ret"
}

# select and mount device
continue_session()
{
    local session= session_name= session_device= dialog_ret=

    while true; do
        session=$(select_saved_session)
        dialog_ret="$?"

        if [ $dialog_ret = "1" ]; then # "Cancel" pressed. Go to higher level
            return 255
        fi

        [ -z "$session" ] && continue # ESC was pressed

        session_name="$(print_session_name "$session")"
        session_device="$(print_session_device "$session")"
       
        mount_partition "$session_device" || continue # result /mnt/$dev

        mount_loop_file "/mnt/$session_device/$session_name.ext3" && break

        msg="$(printf "$(gettext "Can't umount %s. Can't run further with this bug. Exiting.")" "$dev")"
        umount "/mnt/$dev" || fatal "$msg"
    done

    return 0
}

ask_size()
{
    local dev="$1" && shift
    local capacity= free= used=
    local reserve=
    local dialog_quit="123"
    local mnt_dir="/mnt/$dev"

    [ -z "$dev" ] && return 1

    # in MB
    capacity="$(df -P --block-size=1M "$mnt_dir" | tail -n 1 | sed 's/ \+/ /g' | cut -d ' ' -f 2)"
    free="$(df -P --block-size=1M "$mnt_dir" | tail -n 1 | sed 's/ \+/ /g' | cut -d ' ' -f 4)"
    used="$(df -P --block-size=1M "$mnt_dir" | tail -n 1 | sed 's/ \+/ /g' | cut -d ' ' -f 3)"

    # require 300 Mb free space
    if [ "$free" -lt "300" ]; then
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$(gettext "Not enough free space. Select another device.")" 20 75 3>&1 1>&2
        return 1
    fi

    while true; do
        msg="$(printf "$(gettext "How much reserve Mbytes? Total: %s Mb free: %s Mb")" "$capacity" "$free")"
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        reserve=$($DIALOG --output-fd 3 --inputbox "$msg" 20 75 200 3>&1 1>&2)
        dialog_quit="$?"
        if [ "$dialog_quit" -eq 255 ]; then
            # ESC pressed
            continue
        elif [ "$dialog_quit" -eq 1 ]; then
            # Cancel pressed
            return 1
        fi

        # test is integer number. capacity
        if [ "$reserve" -eq "$reserve" 2> /dev/null -a "$reserve" -lt "$free" ]; then
            break
        fi

        $DIALOG --clear --output-fd 3 3>&1 1>&2
        $DIALOG --output-fd 3 --msgbox "$(gettext "Bad input. Try again.")" 20 75 3>&1 1>&2
    done

    echo "$reserve"

    return 0
}

new_session()
{
    local dev= 
    local ret=
    local dialog_ret=
    local reserve_mbytes=
    local index=
    local session_name=

    while true; do
        dev=$(select_dev)
        dialog_ret="$?"

        if [ $dialog_ret = "1" ]; then # "Cancel" pressed. Go to higher level
            return 1
        fi

        [ -z "$dev" ] && continue # ESC was pressed

        mount_partition "$dev" || continue

        reserve_mbytes=$(ask_size $dev) && break

        msg="$(printf "$(gettext "Can't umount %s. Can't run further with this bug. Exiting.")" "$dev")"
        umount "/mnt/$dev" || fatal "$msg" 
    done

    local loop_file="alt_$(date +%Y%m%d)_1.ext3"

    # ignore and leave old sessions
     while [ -f "/mnt/${dev}/${loop_file}" ]; do
         index="${index#alt_????????_}"
         index="${index%.ext3}"
         index=$(($index+1))
         loop_file="alt_$(date +%Y%m%d)_$index.ext3"
     done

    while true; do
        $DIALOG --clear --output-fd 3 3>&1 1>&2
        session_name=$($DIALOG --output-fd 3 --inputbox "$(gettext "Please enter session name:")" 20 75 "$(basename "$loop_file" ".ext3")" 3>&1 1>&2)
        dialog_ret="$?"
        if [ "$dialog_ret" -eq 255 ]; then
            # ESC pressed
            continue
        elif [ "$dialog_ret" -eq 1 ]; then
            # Cancel pressed
            msg="$(printf "$(gettext "Can't umount %s. Can't run further with this bug. Exiting.")" "$dev")"
            umount "/mnt/$dev" || fatal "$msg" 
            return 1
        fi

        [ -z "$session_name" ] && continue

        # test maybe file already exists..... 
        if [ -f "/mnt/$dev/$session_name" ]; then
            $DIALOG --clear --output-fd 3 3>&1 1>&2
            $DIALOG --output-fd 3 --msgbox "$(gettext "Bad input. Try again.")" 20 75 3>&1 1>&2
            continue
        fi

        break
    done

     loop_file="/mnt/${dev}/${session_name}.ext3"

     dd if=/dev/zero of="$loop_file" bs=1M count=$reserve_mbytes > /dev/null 2>&1 || fatal "Can't init loop image"

     # create ext3 fs
     mke2fs -L "$FS_LABEL" -j -F "$loop_file" > /dev/null 2>&1 || fatal "$(gettext "Can't make ext3 on loop image")"

     [ -d "$rwroot" ] || mkdir -p "$rwroot"

     mount -n -t ext3 -o loop "$loop_file" "$rwroot" > /dev/null 2>&1 || fatal "$(gettext "Can't mount loop image")"

     return 0
}

# Mount device to /mnt/$dev
mount_device()
{
    local dev="$1" && shift
    local opt="$1" && shift
    local udev_info=
    local ID_FS_TYPE=
    local mount_dir="/mnt/$dev"
    
    udev_info=$(udevadm info --query=all --name="$dev" 2>/dev/null)
   
    [ -z "$udev_info" ] && return 1

    ID_FS_TYPE="$(get_var "ID_FS_TYPE" "$udev_info")"
    
    [ -z "$ID_FS_TYPE" ] && return 1

    mount_dir="/mnt/$dev"

    [ -d "$mount_dir" ] || mkdir -p "$mount_dir"

    mount -n -t "$ID_FS_TYPE" ${opt:+-o "$opt"} "/dev/$dev" "$mount_dir" >/dev/null 2>&1 || return 1

    return 0
}

# store result in array saved_sessions
find_saved_sessions()
{
    local devices= dev= item=

    devices="$(find_suitable_devices)"

    [ -z "$devices" ] && return 0 # can't find devices with known ID_FS_TYPE

    for dev in $devices; do

        mount_device "$dev" "ro" || continue
        
        for item in $(find "/mnt/$dev" -maxdepth 1 -name "*.ext3" -print 2>/dev/null); do
            # read label of loop
            [ "$FS_LABEL" != "$(e2label "$item")" ] && continue
            saved_sessions[${#saved_sessions[*]}]="$(basename "$item" ".ext3") ($dev)"
        done

        msg="$(printf "$(gettext "can't umount %s from %s")" "$dev" "$mount_dir")"
        umount "/mnt/$dev" || fatal "$msg"
    done
    
    return 0
}

start_interactive()
{
    local choice=
    local dialog_ret=

    find_saved_sessions

    while true; do
        choice=$(dialog_greeting)
        dialog_ret="$?"

        if [ $dialog_ret = "1" ]; then # "Cancel" pressed
            dialog_quit
            return 1
        fi

        [ -z "$choice" ] && continue # ESC was pressed

        case "$choice" in
            "restore")
                      continue_session && break
                      ;;
            "init")
                      new_session && break
                      ;;
            "quit")
                      dialog_quit
                      return 123
                      ;;
            *)
                      child_ret="123" # hmmmmm, i can't be here
            ;;
        esac
    done

    return 0
}

get_dev_size()
{
    local dev= dev_path= size_file= size= whole= remainder= suffix=
    dev="$1" && shift
    test -n "$dev" || return 1

    dev_path=$(udevadm info --query=path --name=$dev 2>/dev/null)
    test -n "$dev_path" || return 1

    size_file="/sys/$dev_path/size"
    test -f "$size_file" || return 1

    size=$(cat "$size_file" 2>/dev/null)
    test -n "$size" || return 1

    # 999.0Bytes 999.0Kb 700.0Mb 1000000.0Gb
    size=$((size*512)) # bytes

    if [ "$size" -lt "1024" ]; then # leave bytes
        suffix="Bytes"
        size="$((size*1024))" # stupid hack
    elif [ "$size" -lt "$((1024*1024))" ]; then # leave Kbytes
        suffix="Kb"
    elif [ "$size" -lt "$((1024*1024*1204))" ]; then # leave Mbytes
        suffix="Mb"
        size="$((size/(1024)))"
    else
        suffix="Gb"
        size="$((size/(1024*1024)))"
    fi

    whole="$((size / 1024))"
    remainder="$(echo "$((size % 1024))" | sed 's/\(.\).*/\1/')"

    echo "${whole}.${remainder}${suffix}"
}

# =======================
# Program start from here
# =======================

interactive=

if [ "$UID" != "0" ] ; then
    msg="$(printf "$(gettext "%s requires root privileges")" "$PROG")"
    fatal "$msg" 
fi

pushd . >/dev/null 2>&1

trap exit_handler EXIT SIGHUP SIGINT SIGQUIT SIGTERM

exec </dev/tty1 >/dev/tty1 2>&1

# /mnt to RW
mount -n -t tmpfs /dev/shm /mnt || fatal "Cant't mount /mnt with tmpfs"
mkdir -p "$rwroot" || fatal "Cant make $rwroot directory"

# (stanv@): don't delete this: (init aufs branches stack).
mountpoint -q /tmp || mount -n -t tmpfs -o nosuid none /tmp || fatal "Can't mount /tmp with tmpfs"
for item in $dirs; do
    mount -n -t aufs -o "ro,br:/${item}=rr" none "/${item}" ||
        fatal "Can't mount $item: mount -n -t aufs -o ro,br:/${item}=rr none /${item}"
done

# default run in batch mode
# check to run in interactive mode
if [ -f "/proc/cmdline" ]; then
    cat "/proc/cmdline" | grep "live_rw" >/dev/null 2>&1 && interactive="yes"
fi

# interactive=1231sss # XXX: go to interactive mode

# set -x
# openvt /bin/bash ||:
if [ -n "$interactive" ]; then
    which dialog > /dev/null 2>&1 || fatal "$PROG requires 'dialog' from dialog package"
    which mke2fs > /dev/null 2>&1 || fatal "$PROD requires 'mke2fs' from e2fsprogs package" 
    if ! [ -f "/proc/cmdline" ]; then
        echo "Cant access /proc/cmdline. Don't worry, English - your language."
    else
        lang="$(grep -o 'lang=[a-zA-Z_]*' /proc/cmdline)"
        lang="${lang#lang=}"
        if [ -n "$lang" -a -x "/bin/unicode_start" ]; then
            /bin/unicode_start
            export LANG="${lang}.UTF-8"
            echo "Now I speak on: $(gettext "this language")"
        fi
    fi

    start_interactive
fi


# if run_dialog_mode fail /mnt still is RW-tmpfs

cat "/proc/cmdline" | tr ' ' '\n' | while read option
do
    echo "${option}" | grep -q -s '^img=' || continue
    img="${option#img=}"
    img="${img%=r[ow]}"
    opt="${option#img=?*=}"
    [ -z "${opt}" ] && opt="ro"
    if ! [ -r "/image/${img}" ]; then
        continue
    fi
    mkdir -p "/mnt/${img}" || continue
    mount -o loop "/image/${img}" "/mnt/${img}" || continue

    for item in $dirs; do
        if ! [ -d "/mnt/${img}/${item}" ]; then
            continue
        fi
        mount -n -t aufs -o "remount,prepend:/mnt/${img}/${item}=${opt}" none "/${item}" ||
            fatal "FAIL: mount -n -t aufs -o remount,prepend:/mnt/${img}/${item}=${opt} none /${item}"
    done
done

popd  > /dev/null 2>&1

if grep -q 'automatic=method:nfs'  /proc/cmdline ; then
	# mount overlays from nfs 
	ip=$(netstat -t --numeric-hosts | grep :nfs | head -n1 | \
		sed 's/  */ /g' | cut -d' ' -f5 | cut -d: -f1)
	mkdir -p /mnt/images
	if mount -o nolock $ip:/srv/public/netinst/overlays-live /mnt/images ; then
		for image in $(find /mnt/images -name '*iso' | sort) ; do
			imgdir=/mnt/overleys/$(basename $image)
			mkdir -p $imgdir
			mount -o loop $image $imgdir
			for dir in $dirs; do
				[ -d $imgdir/$dir ] && \
					mount -t aufs -o "remount,append:$imgdir/$dir=rr" none /$dir
			done
		done
	fi
fi


# Automaitc rw live on flash
if grep -q 'automatic=method:disk,label:ALT' /proc/cmdline && \
	 [ -f /sys/dev/block/$(mountpoint -d /image)/partition ] && \
	[ ! -h /dev/disk/by-label/alt-live-storage ] ; then
	partition=$(mountpoint -d /image)
	major=${partition%:*}
	minor=$((${partition#*:}& ~0xf))
	devlink=$(readlink /sys/dev/block/$major:$minor)
	device=/dev/${devlink##*/}
	before=$(fdisk -l $device | wc -l)
	fdisk $device << _EOF_
n
p



w
_EOF_
	after=$(fdisk -l $device | wc -l)
	if [ $after -gt $before ] ; then 
		partline=$(fdisk -l $device | tail -n1)
		startend=$(echo $partline | sed 's/  */ /g' | cut -d' ' -f2,4)
		number=$(echo $partline | cut -d' ' -f1| sed 's/[^0-9]*//')
		addpart $device $number $startend && sleep 1 && mkfs.ext3 -L alt-live-storage $device$number
		sleep 1;
	fi
fi

if [ -h /dev/disk/by-label/alt-live-storage ] ; then
	[ -d "$rwroot" ] || mkdir -p "$rwroot"
	mount /dev/disk/by-label/alt-live-storage "$rwroot"
fi

exit 0 # Go to exit handler
