#!/bin/sh

expand_mes() {
    source /usr/lib/setup/INSusb.mes
    # source /home/kojima/Build/Get_usb/INSusb.mes
}

# 見つかった最初のUSBメモリしか返さない
# 複数のUSBメモリを認識すべきか？ 
get_usb() {
    tgt=""
    while read -r line ; do 
	chk=`echo $line | grep "Disk model:" | grep -i usb`
	if [ "$chk.x" != ".x" ]; then
	    tgt=$old_line
	    break
	fi
	old_line=$line
    done < <( LANG=C fdisk -l )
    if [ "$tgt.x" != ".x" ] ; then
	usb_dev=`echo $tgt | cut -f2 -d' ' | sed "s/://"`
    fi
}

expand_mes

while [ 0 ]; do
    rm -f /tmp/SeTDS /tmp/SeTmount
    get_usb
    if [ "${usb_dev}.x" == ".x" ]; then
	dialog --title "Cannot found USB memory" --msgbox "$usb_not_found" 14 70
	exit
    fi
    
    # 最初のUSBメモリの先頭パーティション
    # isoイメージベタ書きでない場合はHDDパーティションからのインストールを使えばいいだろう
    tgt_part=${usb_dev}"1"
    echo "USB_DEV:${usb_dev}, Tgt:${tgt_part}"
    while [ 0 ]; do
	expand_mes
	dialog --title "Install from USB memory" --msgbox "$usb_mes" 20 70 2> /tmp/yesno
	if [ $? = 1 -o $? = 255 ]; then
	    rm -f /tmp/yesno
	    exit
	fi
	SUCCESS=false
	clear
	# mount ${tgt_part} /var/adm/mount 1> /dev/null 2> /dev/null
	mount ${tgt_part} /var/adm/mount
	sleep 3
	if [ $? = 0 ]; then # mounted successfully 
	    SUCCESS=true
	    break
	fi
	if [ ! "${SUCCESS}" = "true" ]; then # there was a mount error
	    sleep 5
	    expand_mes
	    dialog --title "Mount error" --menu "$mnterr_mes" 10 68 2 \
		   "Restart" "$mnterr_list01" \
		   "Ignore " "$mnterr_list02" 2> /tmp/dowhat
	    if [ $? = 1 -o $? = 255 ]; then
		rm -f /tmp/dowhat
		exit
	    fi
	    DOWHAT="`cat /tmp/dowhat`"
	    rm -f /tmp/dowhat
	    if [ "$DOWHAT" = "Restart" ]; then
		umount /var/adm/mount 2> /dev/null
		continue;
	    fi
	    echo
	fi # mount error

    done
    SLACK_SOURCE_LOCATION="plamo"
    
    if [ -d /var/adm/mount/${SLACK_SOURCE_LOCATION} ]; then
	echo "/var/adm/mount/${SLACK_SOURCE_LOCATION}" > /tmp/SeTDS
	echo "-source_mounted" > /tmp/SeTmount
	echo "/dev/null" > /tmp/SeTsource
	exit
    else
	expand_mes
	dialog --title "Cannot find packages directory" --yesno "$direrr_mes" 10 70
	if [ $? = 1 -o $? = 255 ]; then
	    rm -f /tmp/tmpmsg
	    exit
	fi
	rm -r /tmp/tmpmsg
    fi
    
    if [ ! -d /var/adm/mount/${SLACK_SOURCE_LOCATION}/00_base ]; then
	expand_mes
	dialog --title "Cannot find categorized directory" --yesno "$nodir_mes" 10 70
	if [ $? = 1 -o $? = 255 ]; then
	    rm -f /tmp/tmpmsg
	    exit
	fi
	rm -r /tmp/tmpmsg
    fi

done
