#!/bin/bash
#
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL 
# Description:
# This is only for "disk to disk" or "partition to partition" clone.

# it is important to run partimage in save mode with volume=0 so that we
# can send the data to stdout
# This is the basic idea for partimage:
# (partimage -z0 -o -d --volume=0 -B gui=no save /dev/hda1 stdout |
#  partimage -M -f3 -b restore /dev/hdc1 stdin)
# Similar idea for ntfsclone and dd.
ocs=$(basename $0)
VOL_ZERO="0"
#create image volumes with a size of X, 
# ignore the MBR by using -M, we will ignore the error caused by devfs style
# in /proc/partitions
DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT="-M -z0 -o -d -b -c -B gui=no --volume=$VOL_ZERO"
DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT="-M -f3 -b"
# port for netcat
NC_PORT_DEFAULT="9000"

# Load DRBL setting and functions
if [ ! -f "/opt/drbl/sbin/drbl-conf-functions" ]; then
  echo "Unable to find /opt/drbl/sbin/drbl-conf-functions! Program terminated!" 
  exit 1
fi
. /opt/drbl/sbin/drbl-conf-functions

# Load some necessary setting from drbl-ocs.conf
. /opt/drbl/conf/drbl-ocs.conf

# Load basic functions of ocs
. /opt/drbl/sbin/ocs-functions

# Load the config in ocs-live.conf. This is specially for Clonezilla live. It will overwrite some settings of /opt/drbl/conf/drbl-ocs.conf, such as $DIA...
[ -e "/etc/ocs/ocs-live.conf" ] && . /etc/ocs/ocs-live.conf

# local functions:
# check if the user input /dev/hda, /dev/hdb...
check_input_param() {
  # return code 3 = disk, return code 5 = partition
  local input_src="$1"
  local recode
  case "$input_src" in
       [hs]d[a-z])
         recode=3
         ;;
       [hs]d[a-z][0-9]*)
         recode=5
         ;;
       *)
        echo "\"$input_src\" $msg_is_unknown_HDdd... $msg_program_stop!"
	echo -n "$msg_press_enter_to_continue"
        read
        exit 1
  esac
  return $recode
} # end of check_input_param
#
check_pt_then_run_sfdisk() {
  echo "$msg_creating_partition_in_target"
  if [ -f "$pt_tmp" ]; then
    echo "$msg_partition_table_for_target_dev \"$target_hd\":"
    echo "-------------------------------------------------------------"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    cat $pt_tmp
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "-------------------------------------------------------------"
    if [ "$batch_mode" = "on" ]; then
      fdisk_ans="y"
    else
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "$msg_are_u_sure_u_want_to_continue $msg_if_go_on_the_data_will_be_erased_then_confirm"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo -n "[y/N] "
      read fdisk_ans
    fi
    case "$fdisk_ans" in
      [yY]|[yY][eE][sS])
         # Turn off swap and LVM2, unlock the busy partitions.
         turn_off_swap_and_LVM2
         sfdisk --force $sfdisk_opt /dev/$target_hd < $pt_tmp
         ;;
      *)
         if [ "$partition_table_exist_in_target" = "no" ]; then
           [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
           echo "No partition table exists in /dev/$target_hd, and you choose not to create partition table in /dev/$target_hd! We can not go on without partition table in /dev/$target_hd!!!"
           [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
           echo "$msg_program_stop!"
           exit 1
         fi
         echo "$msg_ok_we_will_keep_old_partition_table"
         ;;
    esac
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "$msg_fail_to_create_partition_table_in_target_dev: /dev/$tgt_dev! $msg_program_stop!!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
  echo 'done!'
} # end of check_pt_then_run_sfdisk
#
nc_lp_check() {
  NC_LOCAL_PORT_OPT=
  nc_tmp="$(mktemp /tmp/nc_tmp.XXXXXX)"
  # check if command is nc or netcat
  if which nc &>/dev/null; then
     NC_CMD="nc"
  elif which netcat &>/dev/null; then
     NC_CMD="netcat"
  else
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "Unable to find command netcat or nc!!! Program terminated!"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     exit 1
  fi

  LC_ALL=C $NC_CMD -h 2> $nc_tmp
  if [ -n "$(grep -Ei "^[[:space:]]*-p port[[:space:]]+local port number" $nc_tmp)" ]; then
     # This is the version Hobbit wrote (http://www.vulnwatch.org/netcat/)
     # The reason we want to add -q 0 for Hobbit version is that:
     # in Debian, if -q 0 is not set, it will wait forever... nc will not quit.
     # However, in FC3 or ealier version, there is no -q option. nc will quit
     # when EOF.
     [ -n "$(grep "\-q secs" $nc_tmp 2>/dev/null)" ] && NC_QUIT_OPT="-q 0"
     NC_LOCAL_PORT_OPT="$NC_QUIT_OPT -p"
  elif [ -n "$(grep -Ei "^[[:space:]]*-p port[[:space:]]+Specify local port for remote connects" $nc_tmp)" ]; then
     # This is the version Eric Jackson wrote (http://www.monkey.org/~shinobi)
     NC_LOCAL_PORT_OPT=""
  fi
  if [ -n "$(grep -Ei "^[[:space:]]*-d[[:space:]]+Detach from stdin" $nc_tmp)" ]; then
     # if -d is not assigned, it will try to read stdin data, which will cause some problem like this, since it's in the while loop, and while read something from stdin, and nc will also get that if -d is not added:
     # while read logv filesystem; do
     #   nc 192.168.120.2 9006 | lzop -dc | partimage -M -f3 -b -B gui=no restore $logv stdin
     # done < $logv_pse_con
     NC_CLIENT_EXTRA_OPT="-d"
  fi
  [ -f "$nc_tmp" ] && rm -f $nc_tmp
  echo "Using \"-l $NC_LOCAL_PORT_OPT port\" when it's netcat listen mode."
} # end of nc_lp_check

#
kill_clone_prog_nc_process() {
  local i
  echo "Terminate partimage and $NC_CMD processs if they exist..."
  for i in partimage ntfsclone dd $NC_CMD; do
    echo "pkill -u root $i"  && pkill -u root $i
  done
} # end of kill_clone_prog_nc_process
#
clone_boot_loader_in_target() {
echo "$msg_delimiter_star_line"
if [ "$CLONE_BOOT_LOADER" = "yes" ] && [ "$source_type" = "disk" ] && [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then
  if [ "$batch_mode" = "on" ]; then
    mbr_ans="y"
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "$msg_do_you_want_to_clone_the_boot_loader_to: $tgt_dev ?"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "[Y/n] "
    read mbr_ans
  fi
  case "$mbr_ans" in
    n|N|[nN][oO])
       echo "OK, $msg_skip_clone_boot_loader."
       ;;
    *)
       if [ "$mode" = "local" ]; then
         echo "Cloning the boot loader from \"$source_hd\" to \"$target_hd\"..."
         # boot loader is the first 446 Bytes, the rest part is partition table.
         dd if=/dev/$source_hd of=/dev/$target_hd bs=446 count=1 &> /dev/null
         ret=$?
       elif [ "$STATUS" = "clone_client" ]; then
         echo "Cloning the boot loader from that in $SOURCE_IP to \"$target_hd\"..."
         # boot loader is the first 446 Bytes, the rest part is partition table.
         dd if=$hd_tgt_tmp/mbr of=/dev/$target_hd bs=446 count=1 &> /dev/null
         ret=$?
       fi
       if [ "$ret" -ge 1 ]; then
         [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
         echo "$msg_failed_to_clone_the_boot_loader: \"$target_hd\"!!!"
         echo "$msg_program_stop!!"
         [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
         exit 1
       fi
       ;;
  esac
fi
} # end of clone_boot_loader_in_target
#
create_partition_table_in_target(){
if [ "$RUN_SFDISK" != "no" ]; then
  echo "$msg_delimiter_star_line"
  if [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then 
    # try to see if the partition table exists in the target 
    if [ -n "$(LC_ALL=C fdisk -l /dev/$target_hd 2>/dev/null | grep -E "/dev/[sh]d[a-z][0-9]+")" ] ; then
      partition_table_exist_in_target="yes"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "$msg_a_partition_table_already_exist: \"$target_hd\""
      echo "-------------------------------------------------------------"
      LC_ALL=C fdisk -l /dev/$target_hd
      echo "-------------------------------------------------------------"
    else
      partition_table_exist_in_target="no"
    fi
    check_pt_then_run_sfdisk
  fi
fi
} # end of create_partition_table_in_target
#
confirm_do_it_in_target_dev() {
if [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then
  echo "$msg_delimiter_star_line"
  echo "$msg_target_dev_has_this_partition_table:"
  # try to see if the partition table exists in the target 
  echo "$msg_delimiter_star_line"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  LC_ALL=C fdisk -l /dev/$target_hd
  echo "$msg_delimiter_star_line"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_uppercase_Warning!!! $msg_uppercase_Warning!!! $msg_uppercase_Warning!!!"
  echo "$msg_uppercase_Warning! $msg_all_data_in_dev_will_be_overwritten: $tgt_dev"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  if [ "$batch_mode" = "on" ]; then
    do_ans="y"
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "$msg_are_u_sure_u_want_to_continue ?"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "[y/N] "
    read do_ans
  fi
  case "$do_ans" in
    [yY]|[yY][eE][sS])
       echo "$msg_ok_let_do_it"
       ;;
    *)
       exit 1
       ;;
  esac
fi
} # end of confirm_do_it_in_target_dev
#
local_lvm_clone_warning() {
  if [ "$part_fs" = "lvm" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Local LVM clone is not well supported, since in the same system, no two same PV UUID can co-exist. Use dd to do sector-to-sector copy. On the other hand, a workaround is available. You can use network clone using two separate machines in clonezilla to avoid this problem. For more details, check http://clonezilla.sf.net for more details. "
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
} # end of local_lvm_clone_warning
#
prepare_local_clone_dev_info() {
  local_tmp="$(mktemp -d /tmp/ocs_onthefly_local.XXXXXX)"
  # since it's local, target tmp dir is the same one with local_tmp
  hd_tgt_tmp="$local_tmp"
  pt_tmp="$hd_tgt_tmp/pt.sf"
  pt_info="$hd_tgt_tmp/partition.info"

  # Note! In Ubuntu 6.10, sfdisk output abnormal format for >= 10 partitions, like
  #...
  #/dev/hda9 : start=  1277703, size=   196497, Id=83
  #/dev/hda10: start=  1474263, size=   196497, Id=83
  #/dev/hda11: start=  1670823, size=   196497, Id=83
  #/dev/hda12: start=  1867383, size= 14909202, Id=83
  # Therefor later we have to use  "sed -e "s/:$//g" to clean that.
  #
  # Here we want to output the filesystem of partition to be refered by client.
  # Ex:
  # /dev/hda1 reiserfs
  # /dev/hda2 ext3
  sfdisk -d /dev/$source_hd > $pt_tmp
  for part in `grep -i "Id=" $pt_tmp | cut -d" " -f1 | sed -e "s/:$//g"`; do
    echo "Collecting partition $part info..."
    filesystem="$(get_part_info $part filesystem)"
    pt_size="$(get_part_info $part size)"
    echo "$part $filesystem $pt_size" >> $pt_info
  done
  # SWAP partition info, maybe more than 1
  for partition in `cat $pt_tmp | grep "Id=82" | cut -d" " -f1 | sed -e 's/\/dev\///g'`
  do
    echo "Outputing swap UUID/LABEL..."
    # change the target swap partition, like hda2 -> hdb2
    target_swap_part_info="$(echo swappt-${partition}.info | sed -e "s|[hs]d[a-z]|$target_hd|g")"
    output_swap_partition_uuid_label /dev/$partition $local_tmp/$target_swap_part_info
  done
  # change the dev to target in the $pt_tmp and $pt_info
  LC_ALL=C perl -p -i -e "s|/dev/[hs]d[a-z]|/dev/$target_hd|g" $pt_tmp
  LC_ALL=C perl -p -i -e "s|/dev/[hs]d[a-z]|/dev/$target_hd|g" $pt_info
  ret_pt_sf=$?
} # end of prepare_local_clone_dev_info
#
prepare_network_clone_dev_info() {
  local DEV VG UUID LOGV
  if [ "$STATUS" = "clone_server" ]; then
    pt_tmp=$hd_src_tmp/pt.sf
    pt_info="$hd_src_tmp/partition.info"
    # partition table
    # Note! In Ubuntu 6.10, sfdisk output abnormal format for >= 10 partitions, like
    #...
    #/dev/hda9 : start=  1277703, size=   196497, Id=83
    #/dev/hda10: start=  1474263, size=   196497, Id=83
    #/dev/hda11: start=  1670823, size=   196497, Id=83
    #/dev/hda12: start=  1867383, size= 14909202, Id=83
    # Therefor later we have to use  "sed -e "s/:$//g" to clean that.
    sfdisk -d /dev/$source_hd > $pt_tmp
    # The output of CHS is ${source_hd}-chs.sf
    output_HD_CHS $source_hd $hd_src_tmp/
    mv -f $hd_src_tmp/${source_hd}-chs.sf $hd_src_tmp/chs.sf
    # MBR
    dd if=/dev/$source_hd of=$hd_src_tmp/mbr count=1 bs=512 &> /dev/null
    # output the filesystem of partition to be refered by client. Ex:
    # /dev/hda1 reiserfs
    # /dev/hda2 ext3
    for part in `grep -i "Id=" $pt_tmp | cut -d" " -f1 | sed -e "s/:$//g"`; do
      echo "Collecting partition $part info..."
      filesystem="$(get_part_info $part filesystem)"
      pt_size="$(get_part_info $part size)"
      echo "$part $filesystem $size" >> $hd_src_tmp/partition.info
    done
    # SWAP partition info, maybe more than 1
    for partition in `cat $pt_tmp | grep "Id=82" | cut -d" " -f1 | sed -e 's/\/dev\///g'`
    do
      echo "Outputing swap UUID/LABEL..."
      output_swap_partition_uuid_label /dev/$partition $hd_src_tmp/swappt-${partition}.info
    done
    # LVM
    PV_PARSE_CONF="$hd_src_tmp/lvm_vg_dev.list"
    LOGV_PARSE_CONF="$hd_src_tmp/lvm_logv.list"
    $DRBL_SCRIPT_PATH/sbin/lvm2-start.sh
    echo "Parsing LVM layout..."
    pvscan | grep lvm2 | while read LINE; do
      DEV=`echo $LINE | tr -s ' ' | cut -d' ' -f2`
      VG=`echo $LINE | tr -s ' ' | cut -d' ' -f4`
      # DEV is like /dev/hda2
      # We just want to keep the chosen source dev
      # The results in $PV_PARSE_CONF is like:
      # ----------------------------------------------------
      # vg /dev/hda2 qdlt6U-M4bo-xExy-XG9Q-U7pg-bOXN-n54i5Y
      # ----------------------------------------------------
      # Ex: target: hda1 hda2 hda3, DEV maybe: /dev/hda2
      if [ -n "$(echo "$DEV" | grep -E "$source_hd")" ]; then
        UUID="$(pvdisplay $DEV | grep "PV UUID" | awk -F" " '{print $3}')"
        echo "$VG $DEV $UUID" | tee -a $PV_PARSE_CONF
      fi
    done
    
    if [ -e "$PV_PARSE_CONF" ]; then
      # We just want the LV in chosen target
      echo "Parsing logical volumes..."
      # lvscan results are like:
      # ACTIVE            '/dev/vg3/lvol0' [1.20 GB] inherit
      # ACTIVE            '/dev/vg3/lvol1' [648.00 MB] inherit
      # ACTIVE            '/dev/vg/lvol0' [1.50 GB] inherit
      # ACTIVE            '/dev/vg/lvol1' [500.00 MB] inherit
      #                         ^^ The VG
      
      # find LV for chosen PV.
      lvscan | grep "/.*/" | while read LINE; do
        LOGV=`echo $LINE |tr -s ' ' | cut -d' ' -f2 | tr -d "'"`
        # LOGV is like: /dev/vg3/lvol0
        while read vg dev uuid; do
         # only keep LOGV is in the chosen vg
         if [ -n "$(echo $LOGV | grep -E "/dev/$vg/" 2>/dev/null)" ]; then
          file_system="$(get_part_info $LOGV filesystem)"
          echo "$LOGV $file_system" | tee -a $LOGV_PARSE_CONF
	  # if it's swap, output the labe and uuid only.
	  case "$file_system" in 
            *[Ss][Ww][Aa][Pp]*)
              fn="$(echo $LOGV | sed -e "s|^/dev/||" -e "s|/|-|g")"
              output_swap_partition_uuid_label $LOGV $hd_src_tmp/swappt-${fn}.info
              continue ;;
            *extended*) 
              continue ;;
          esac
          break
         fi 
        done < $PV_PARSE_CONF
      done
      
      # Backup the vg conf
      echo "Saving the VG config... "
      while read vg dev uuid; do
        vgcfgbackup -f $hd_src_tmp/lvm_$vg.conf $vg 2>/dev/null
      done < $PV_PARSE_CONF
      echo "done!"
    fi
    cat <<-ADVAN_PARAM_END > $hd_src_tmp/advanced_param.conf
batch_mode="$batch_mode" 
install_grub="$install_grub"
grub_partition="$grub_partition" 
RUN_SFDISK="$RUN_SFDISK" 
CLONE_BOOT_LOADER="$CLONE_BOOT_LOADER" 
resize_partition="$resize_partition" 
load_HD_CHS="$load_HD_CHS" 
nogui="$nogui" 
verbose="$verbose" 
ADVAN_PARAM_END
    $DRBL_SCRIPT_PATH/sbin/lvm2-stop.sh
    # pack all the info files
    ( 
      cd $hd_src_tmp/
      tar czf ocs-onthefly-info.tgz *
    )
    # wait for client to download it
    cat $hd_src_tmp/ocs-onthefly-info.tgz | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
    NC_PORT=$((NC_PORT + 2))
  elif [ "$STATUS" = "clone_client" ]; then
    # Get the pt and mbr... from server
    $NC_CMD $NC_CLIENT_EXTRA_OPT $SOURCE_IP $NC_PORT > $hd_tgt_tmp/ocs-onthefly-info.tgz
    NC_PORT=$((NC_PORT + 2))
    if [ ! -f "$hd_tgt_tmp/ocs-onthefly-info.tgz" ]; then
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "The partition table, MBR infomation is not received from another machine (IP address $SOURCE_IP)!"
      echo "$msg_program_stop"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      exit 1
    fi
    ( 
      cd $hd_tgt_tmp/
      tar xzf ocs-onthefly-info.tgz
    )
    # read advanced param passed from server
    . $hd_tgt_tmp/advanced_param.conf

    # partition table and info
    pt_tmp="$hd_tgt_tmp/pt.sf"
    pt_info="$hd_tgt_tmp/partition.info"
    # change the dev to target in the $pt_tmp nd $pt_info
    LC_ALL=C perl -p -i -e "s|/dev/[hs]d[a-z]|/dev/$target_hd|g" $pt_tmp
    LC_ALL=C perl -p -i -e "s|/dev/[hs]d[a-z]|/dev/$target_hd|g" $pt_info
    # FIXME! get sfdisk_opt if load_HD_CHS is yes
    [ "$load_HD_CHS" = "yes" ] && load_HD_geometry $hd_tgt_tmp/
  fi
} # end of prepare_network_clone_dev_info
#
local_partition_to_partiton_clone() {
  local pt_fs="$1"
  local src_p="$2"  # src_p is like /dev/hda1
  local tgt_p="$3"  # tgt_p is like /dev/hdb1
  local pt_size ret dd_img_info_tmp dd_report_sig_pid start_time end_time
  echo "Cloning the $src_p to $tgt_p..."
  clean_filesystem_header_in_partition $tgt_p
  # From partimage 0.6.6, batch mode won't stop if checkInodeForDevice is not run. Therefore comment it.
  # checkInodeForDevice $tgt_p
  echo "$msg_delimiter_star_line"
  if [ "$pt_fs" = "ntfs" ]; then
    echo "Using ntfsclone to clone..."  
    check_ntfs_partition_integrity $src_p
    ntfsclone --save-image --output - $src_p 2>/dev/null | \
    ntfsclone --restore-image --overwrite $tgt_p -
    ret=$?
  elif `is_partimage_support_fs $pt_fs`; then
    echo "Using partimage to clone..."  
    partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save $src_p stdout 2> /dev/null | \
    partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT $PARTIMAGE_RESTORE_EXTRA_OPT restore $tgt_p stdin
    ret=$?
  else
    local_lvm_clone_warning
    echo "Filesystem in $src_p is not well supported. Use dd to clone..."  
    dd_img_info_tmp="$(mktemp /tmp/dd_info.XXXXXX)"
    pt_size="$(get_part_info $tgt_p size)"
    trigger_dd_status_report $tgt_p $pt_size &
    dd_report_sig_pid=$!
    start_time="$(date +%s%N)"
    LC_ALL=C dd bs=1M if=$src_p of=$tgt_p 2>&1 | tee $dd_img_info_tmp
    ret=$?
    end_time="$(date +%s%N)"
    kill -9 $dd_report_sig_pid &>/dev/null
    get_dd_image_info $dd_img_info_tmp $start_time $end_time
    [ -f "$dd_img_info_tmp" ] && rm -f $dd_img_info_tmp
  fi
  echo "$msg_delimiter_star_line"
  if [ "$ret" -ge 1 ]; then
     echo "Failed to clone $src_p to $tgt_p!!!"
     echo "$msg_program_stop!!"
     exit 1
  fi
} # end of local_partition_to_partiton_clone
#
local_dev_clone() {
  # TODO!
  # local LVM clone not yet. The difficulty is in the same system, VG can not use the same UUID. If we clone hda to hdb, VG in hda will have same UUID with that in hdb. Therefore in this function, dd is the last choice temporarily.
  case "$source_type" in
    partition)
       part_fs="$(grep -Ew "/dev/$tgt_dev" $pt_info | awk -F" " '{print $2}')"
       local_partition_to_partiton_clone $part_fs /dev/$src_dev /dev/$tgt_dev
       ;;
    disk)
       for target_part in `get_known_partition_sf_format $pt_tmp`; do
         # we need to know the source partition, so replace it, ex. hdc1 -> hda1
         # Ex: target_part: hdc1, hddev: hdc, part_no: 1, src_part: hda1
         hddev=${target_part:0:3}
         part_no=${target_part:3}
         src_part=$( echo $target_part | sed -e "s/$hddev/$source_hd/g" )
         part_fs="$(grep -Ew "/dev/$target_part" $pt_info | awk -F" " '{print $2}')"
         local_partition_to_partiton_clone $part_fs /dev/$src_part /dev/$target_part
       done
       ;;
  esac
} # end of local_dev_clone
#
feed_dev_in_server() {
  local pt_fs="$1"
  local src_p="$2"  # src_p is like /dev/hda1
  local ret
  echo "Feeding partition $src_p in listen mode with port $NC_PORT..."
  if [ "$pt_fs" = "ntfs" ]; then
    echo "Using ntfsclone to clone..."  
    check_ntfs_partition_integrity $src_p
    ntfsclone --save-image --output - $src_p 2>/dev/null | \
    $filter_comp | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
    ret=$?
  elif `is_partimage_support_fs $pt_fs`; then
    echo "Using partimage to clone..."  
    [ "$verbose" = "on" ] && echo "partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save $src_p stdout 2> /dev/null | $filter_comp | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &"
    partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save $src_p stdout 2> /dev/null | \
    $filter_comp | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
    ret=$?
  else
    echo "Filesystem in $src_p is not well supported. Use dd to clone..."  
    LC_ALL=C dd bs=1M if=$src_p | \
    $filter_comp | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
    ret=$?
  fi
  echo "$msg_delimiter_star_line"
  if [ "$ret" -ge 1 ]; then
     echo "Failed to feeding partition $src_p in this server!!!"
     echo "$msg_program_stop!!"
     exit 1
  fi
} # end of feed_dev_in_server
#
receive_partition_from_server_then_write() {
  local	pt_fs="$1"
  local tgt_p="$2"  # tgt_p is like /dev/hda1
  local ret pt_size
  echo "Restoring $tgt_p from $SOURCE_IP:$NC_PORT..."
  clean_filesystem_header_in_partition $tgt_p
  # From partimage 0.6.6, batch mode won't stop if checkInodeForDevice is not run. Therefore comment it.
  # checkInodeForDevice $tgt_p
  echo "$msg_delimiter_star_line"
  if [ "$pt_fs" = "ntfs" ]; then
    echo "Using ntfsclone to clone..."  
    $NC_CMD $NC_CLIENT_EXTRA_OPT $SOURCE_IP $NC_PORT | $filter_decomp | \
    ntfsclone --restore-image --overwrite $tgt_p -
    ret=$?
  elif `is_partimage_support_fs $pt_fs`; then
    echo "Using partimage to clone..."  
    [ "$verbose" = "on" ] && echo "$NC_CMD $NC_CLIENT_EXTRA_OPT $SOURCE_IP $NC_PORT | $filter_decomp | partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT $PARTIMAGE_RESTORE_EXTRA_OPT restore $tgt_p stdin"
    $NC_CMD $NC_CLIENT_EXTRA_OPT $SOURCE_IP $NC_PORT | $filter_decomp | \
    partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT $PARTIMAGE_RESTORE_EXTRA_OPT restore $tgt_p stdin
    ret=$?
  else
    echo "Filesystem in $src_p is not well supported. Use dd to clone..."  
    pt_size="$(grep -Ew "$tgt_p" $pt_info | awk -F" " '{print $3}')"
    trigger_dd_status_report $tgt_p $pt_size &
    $NC_CMD $NC_CLIENT_EXTRA_OPT $SOURCE_IP $NC_PORT | $filter_decomp | \
    LC_ALL=C dd bs=1M of=$tgt_p
    ret=$?
  fi
  if [ "$ret" -ge 1 ]; then
     echo "Failed to clone remote image to $tgt_p!!!"
     echo "$msg_program_stop!!"
     exit 1
  fi
} # end of receive_partition_from_server_then_write
#
feed_partition_or_lv_in_server() {
  local pt_fs="$1"
  local src_p="$2" # src_p is like hda1
  local lv volg is_in_chosen_partition fs
  # $NC_PORT & $LOGV_PARSE_CONF are global variables.
  [ -z "$pt_fs" ] && echo "pt_fs not found in function feed_partition_or_lv_in_server!" && exit 1
  [ -z "$src_p" ] && echo "src_p not found in function feed_partition_or_lv_in_server!" && exit 1
  if [ -z "$(echo "$pt_fs" | grep -i lvm)" ]; then
    feed_dev_in_server $pt_fs /dev/$src_p
    # use the next port to avoid being occupied.
    NC_PORT=$((NC_PORT + 2))
  else
    $DRBL_SCRIPT_PATH/sbin/lvm2-start.sh
    while read lv fs; do
     # Process the real data partition, only those in the chosen partitions
     # Ex:
     # /dev/vg3/lvol0  Linux rev 1.0 ext3 filesystem data (large files)
     # Then lvol0 is belong to VG vg3
     volg="$(echo "$lv" | awk -F"/" '{print $3}')"
     # Find if the LV is in the chosen partition (via VG, we can determine that)
     # EX: tgt_parts: hda1, hda3, hda5...
     #     vg3 /dev/hda3 nPMQQ0-D2yN-YRHL-9fBM-0cUm-vgcw-DCUTri
     is_in_chosen_partition="no"
     for ipt in $src_p; do
       if [ -n "$(grep -E "[[:space:]]+/dev/$ipt[[:space:]]+" $PV_PARSE_CONF | grep -E "\<$volg\>")" ]; then
         # Found the chosen partitions is in the VG
         is_in_chosen_partition="yes"
         break
       fi
     done
     [ "$is_in_chosen_partition" = "no" ] && continue
     # if it's swap, output the labe and uuid only.
     case "$fs" in 
       *[Ss][Ww][Aa][Pp]*|*extended*)
         continue ;;
     esac
     feed_dev_in_server $fs $lv
     # use the next port to avoid being occupied.
     NC_PORT=$((NC_PORT + 2))
    done < $LOGV_PARSE_CONF
  fi
} # end of feed_partition_or_lv_in_server() {
#
receive_partition_or_lv_in_client() {
 local pt_fs="$1"
 local tgt_p="$2" # tgt_p is like hda1
 local vg dev uuid lf fs fn uuid_opt label_opt pv_pse_con logv_pse_con
 # $NC_PORT & $hd_tgt_tmp are global variables.
 if [ -z "$(echo "$pt_fs" | grep -i lvm)" ]; then
   receive_partition_from_server_then_write $pt_fs /dev/$tgt_p
   # use the next port to avoid being occupied.
   NC_PORT=$((NC_PORT + 2))
 else
   pv_pse_con="$hd_tgt_tmp/lvm_vg_dev.list"
   logv_pse_con="$hd_tgt_tmp/lvm_logv.list"
   [ ! -f "$pv_pse_con" ] && echo "$pv_pse_con NOT found!" && exit 1
   [ ! -f "$logv_pse_con" ] && echo "$logv_pse_con NOT found!" && exit 1
   $DRBL_SCRIPT_PATH/sbin/lvm2-stop.sh

   # Clean the filesystem header in partition where PV exists
   # This is an insurance, since later when we use partimage/ntfsclone to clone, it will not overwrite file header in that partition, it will only overwrite the data in LV. Then parted, blkid will give wrong info.
   while read lv fs; do
    # Process the real data partition, only those in the chosen partitions
    # Ex:
    # /dev/vg3/lvol0  Linux rev 1.0 ext3 filesystem data (large files)
    # Then lvol0 is belong to VG vg3
    volg="$(echo "$lv" | awk -F"/" '{print $3}')"
    # Find if the LV is in the chosen partition (via VG, we can determine that)
    # EX: tgt_parts: hda1, hda3, hda5...
    #     vg3 /dev/hda3 nPMQQ0-D2yN-YRHL-9fBM-0cUm-vgcw-DCUTri
    is_in_chosen_partition="no"
    for ipt in $tgt_p; do
      if [ -n "$(grep -E "[[:space:]]+/dev/$ipt[[:space:]]+" $pv_pse_con | grep -E "\<$volg\>")" ]; then
        # Found the chosen partitions is in the VG
        clean_filesystem_header_in_partition /dev/$ipt
      fi
    done
   done < $logv_pse_con

   # create PV first
   echo "Creating the PV... "
   while read vg dev uuid; do
     pvcreate -ff --yes --uuid $uuid $dev
   done < $pv_pse_con
   echo "done!"

   # Restore the vg conf
   echo "Restoring the VG config... "
   while read vg dev uuid; do
     vgcfgrestore -f $hd_tgt_tmp/lvm_$vg.conf $vg 2>/dev/null
   done < $pv_pse_con
   echo "done!"

   $DRBL_SCRIPT_PATH/sbin/lvm2-start.sh
   while read lv fs; do
    # Process the real data partition, only those in the chosen partitions
    # Ex:
    # /dev/vg3/lvol0  Linux rev 1.0 ext3 filesystem data (large files)
    # Then lvol0 is belong to VG vg3
    volg="$(echo "$lv" | awk -F"/" '{print $3}')"
    # Find if the LV is in the chosen partition (via VG, we can determine that)
    # EX: tgt_parts: hda1, hda3, hda5...
    #     vg3 /dev/hda3 nPMQQ0-D2yN-YRHL-9fBM-0cUm-vgcw-DCUTri
    is_in_chosen_partition="no"
    for ipt in $tgt_p; do
      if [ -n "$(grep -E "[[:space:]]+/dev/$ipt[[:space:]]+" $pv_pse_con | grep -E "\<$volg\>")" ]; then
        # Found the chosen partitions is in the VG
        is_in_chosen_partition="yes"
        break
      fi
    done
    [ "$is_in_chosen_partition" = "no" ] && continue
    # if it's swap, output the labe and uuid only.
    case "$fs" in 
      *[Ss][Ww][Aa][Pp]*)
        fn="$(echo $lv | sed -e "s|^/dev/||" -e "s|/|-|g")"
        echo "Found the swap partition $lv, create it by:"
        # read LABEL, UUID info for $partition if swappt-${fn}.info exists
        uuid_opt=""
        label_opt=""
        if [ -e "$hd_tgt_tmp/swappt-${fn}.info" ]; then
          UUID=""
          LABEL=""
          . "$hd_tgt_tmp/swappt-${fn}.info"
          [ -n "$UUID" ] && uuid_opt="-U $UUID"
          [ -n "$LABEL" ] && label_opt="-L $LABEL"
        fi
        echo "mkswap-uuid $label_opt $uuid_opt $lv"
        mkswap-uuid $label_opt $uuid_opt $lv
        echo $msg_delimiter_star_line
        continue ;;
      *extended*) 
        continue ;;
    esac
    receive_partition_from_server_then_write $fs $lv
    # use the next port to avoid being occupied.
    NC_PORT=$((NC_PORT + 2))
   done < $logv_pse_con
 fi
} # end of receive_partition_or_lv_in_client
#
clone_over_net() {
  local fn example_target
  # try to get the client's type
  case "$source_type" in
    partition)
       if [ "$STATUS" = "clone_server" ]; then
         echo "Running the clone server for $src_dev in port $NC_PORT..."
         part_fs="$(grep -Ew "/dev/$src_dev" $pt_info | awk -F" " '{print $2}')"
	 feed_partition_or_lv_in_server $part_fs $src_dev
       elif [ "$STATUS" = "clone_client" ]; then
         echo "Restoring $tgt_dev from $SOURCE_IP:$NC_PORT..."
         part_fs="$(grep -Ew "/dev/$tgt_dev" $pt_info | awk -F" " '{print $2}')"
	 receive_partition_or_lv_in_client $part_fs $tgt_dev
       fi
       example_target="hda1 or hda2 or sda1 or..."
       ;;
    disk)
       for target_part in `get_known_partition_sf_format $pt_tmp`; do
         # we need to know the source partition, so replace it, ex. hdc1 -> hda1
         # Ex: target_part: hdc1, hddev: hdc, part_no: 1, src_part: hda1
         hddev=${target_part:0:3}
         part_no=${target_part:3}
         src_part=$( echo $target_part | sed -e "s/$hddev/$source_hd/g" )
         if [ "$STATUS" = "clone_server" ]; then
           part_fs="$(grep -Ew "/dev/$src_part" $pt_info | awk -F" " '{print $2}')"
	   feed_partition_or_lv_in_server $part_fs $src_part
         elif [ "$STATUS" = "clone_client" ]; then
           part_fs="$(grep -Ew "/dev/$target_part" $pt_info | awk -F" " '{print $2}')"
	   receive_partition_or_lv_in_client $part_fs $target_part
         fi
       done
       example_target="hda or hdb or sda or..."
       ;;
  esac
  echo "$msg_delimiter_star_line"
  [ -n "$filter" ] && filter_opt="-i $filter"
  if [ "$STATUS" = "clone_server" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "$msg_now_run_this_cmd_in_target_machine:"
    echo "$DRBL_SCRIPT_PATH/sbin/ocs-live-netcfg ($msg_setup_network_first)"
    echo "$DRBL_SCRIPT_PATH/sbin/$ocs $filter_opt --source-IP $my_ips -t [TARGET_DEV]"
    echo "TARGET_DEV example: $example_target"
    case "$source_type" in
      partition)
      echo "$msg_if_clone_the_partition_to_hda1_in_target_machine:"
      echo "$DRBL_SCRIPT_PATH/sbin/$ocs $filter_opt --source-IP $my_ips -t hda1"
      ;;
    disk)
      echo "$msg_if_clone_the_disk_to_hda_in_target_machine:"
      echo "$DRBL_SCRIPT_PATH/sbin/$ocs $filter_opt --source-IP $my_ips -t hda"
      ;;
    esac
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
} # end of clone_over_net
#
post_process_in_target_dev() {
  local local_disk_grub_opt target_parts
  # create swap partition, resize partition, clean the temp partition table, and re-install grub
  if [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then
    echo "$msg_delimiter_star_line"
    #
    if [ "$resize_partition" = "on" ]; then
     case "$source_type" in
       partition) target_parts="$tgt_dev" ;;
       disk) target_parts="$(get_known_partition_sf_format $pt_tmp)" ;;
     esac
     for partition in $target_parts; do
       # hda1 -> hd_tmp, part_no_tmp ,i.e => hda, 1 
       hd_tmp="${partition:0:3}"
       part_no_tmp="${partition:3}"
       echo "Now resize the partition for $hd_tmp$part_no_tmp"
       $DRBL_SCRIPT_PATH/sbin/resize_part $hd_tmp $part_no_tmp
       echo $msg_delimiter_star_line
     done
    fi
    #
    echo "Creating the swap partition if exists..."
    # swap partition
    for partition in `cat $pt_tmp | grep "Id=82" | cut -d" " -f1 | sed -e 's/\/dev\///g'`
    do
      echo "Found the swap partition /dev/$partition, create it by:"
      # read LABEL, UUID info for $partition if swappt-$partition.info exists
      uuid_opt=""
      label_opt=""
      if [ -e "$hd_tgt_tmp/swappt-$partition.info" ]; then
        UUID=""
        LABEL=""
        . "$hd_tgt_tmp/swappt-$partition.info"
        [ -n "$UUID" ] && uuid_opt="-U $UUID"
        [ -n "$LABEL" ] && label_opt="-L $LABEL"
      fi
      echo "mkswap-uuid $label_opt $uuid_opt /dev/$partition"
      mkswap-uuid $label_opt $uuid_opt /dev/$partition
    done
    echo "$msg_delimiter_star_line"
    # clean the tmp file
    [ -f "$pt_tmp" ] && rm -f $pt_tmp
    # Since it's local clone, we must assign the target hardisk, otherwise it might find the source hardisk. For example, hda -> hdc local clone, if no "-s $target_hd" is assigned, it will find hda as grub target.
    [ "$mode" = "local" ] && local_disk_grub_opt="-s $target_hd"
    [ "$install_grub" = "on" ] && install_grub_hd $local_disk_grub_opt $grub_partition
    echo "$msg_delimiter_star_line"
  fi
} # end of post_process_in_target_dev
#
set_filter_program() {
case "$filter" in
  gzip|gz)
       if which gzip &>/dev/null; then
         filter_comp="gzip -c $extra_gzip_opt"
         filter_decomp="gzip -cd"
       else
         [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
         echo "gzip is NOT found! Program terminated!!!"
         [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	 exit 1
       fi
       ;;
  bzip|bzip2)
       if which bzip2 &>/dev/null; then
         filter_comp="bzip2 -c"
         filter_decomp="bzip2 -cd"
       else
         [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
         echo "bzip2 is NOT found! Program terminated!!!"
         [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	 exit 1
       fi
       ;;
   cat)
       filter_comp="cat"
       filter_decomp="cat"
       ;;
   *)
       if which lzop &>/dev/null; then
         filter_comp="lzop -c"
         filter_decomp="lzop -cd"
       else
         [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
         echo "lzop is NOT found! Program terminated!!!"
         [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	 exit 1
       fi
       ;;
esac
} # end of set_filter_program
#
pre_checking() {
# check if it runs in DRBL server and it's not DRBL/Clonezilla live, if yes, warn user!
if [ -d "$pxecfg_pd" -a ! -d "/live_media" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_Warning!!! $msg_should_not_run_ocs_onthefly_in_server"
  echo "$msg_are_u_sure_u_want_to_continue ?"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "[y/N]"
  read clone_ans
  case "$clone_ans" in
	  [y|Y][eE][sS])
          [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
	  echo "$msg_really_dangerous_then_continue"
          [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	  echo -n "$msg_press_enter_to_continue"
	  read
	  ;;
	  *)
	  exit 0
	  ;;
  esac
fi

# check grub_partition if we want to install grub
if [ "$install_grub" = "on" ]; then
  if [ -z "`echo $grub_partition | grep "/dev/[sh]d[a-z][1-9]*"`" -a "$grub_partition" != "auto" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "\"$grub_partition\" $msg_is_not_valid_grub_root! $msg_program_stop!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    exit 1
  fi
fi

#
if [ "$mode" = "local" ]; then
  # check if source and target are the same one if it's local clone!!!
  # we do not accept hda -> hda or hda2 -> hda2, however, hda2 -> hda3 is ok.
  if [ "$tgt_dev" = "$src_dev" ]; then
    echo "$msg_src_target_r_same_dev ($src_dev -> $tgt_dev) $msg_program_stop"
    exit 1
  fi
fi
} # end of pre_checking

#
USAGE() {
    echo "Usage:"
    echo "To run clonezilla on-the-fly:"
    echo "$ocs [OPTION]"
    echo "Option"
    echo "-b, --batch-mode   Run clone in batch mode (DANGEROUS!)"
    echo "-e, --resize-partition   Resize the target disk in target machine (To solve the small partition image restored to larger partition problem.)"
    echo "-f, --source DEV         Specify the source device as DEV (hda, hda1...)"
    echo "-g, --grub-install GRUB_PARTITION     install grub in hda with root grub directory in GRUB_PARTITION when restoration finishs, GRUB_PARTITION can be one of \"/dev/hda1\", \"/dev/hda2\"... or \"auto\" (\"auto\" will clonezilla detects the grub root partition automatically)"
    echo "-i, --filter PROGRAM     Use the PROGRAM (gzip/lzop/bzip2/cat) before sending partition data to netcat (only in network clone mode). The default action is lzop. Use \"cat\" if you do not want to compress (Good for fast internode network)."
    echo "--nogui                  Do NOT show GUI of partimage, use text only"
    echo "-n, --no-sfdisk          Do NOT create partition table in boot sector in target machine"
    echo "-m, --no-boot-loader-clone  Do NOT clone boot loader"
    echo "-o, --load-geometry      Force to use the saved CHS (cylinders, heads, sectors) when using sfdisk in restoring."
    echo "-p, --port PORT          Specify the netcat port (Only in network clone mode)"
    echo "-r, --server             Specify the running machine is in network clone server."
    echo "-s, --source-IP IP       Specify the source IP address (used in target client machine)."
    echo "-t, --target DEV         Specify the target device as DEV (hda, hda1...)"
    echo "-v, --verbose            Prints verbose information"
    echo "-x, --interactive        Interactive mode."
    echo "Ex:"
    echo "1. To clone local hda to local hdb, run"
    echo "   $ocs -f hda -t hdb"
    echo "2. To clone hda (in machine A with IP 192.168.100.1) to hda (in machine B) via network,"
    echo "   In machine A, boot it into DRBL client mode, then run"
    echo "   $ocs -r -f hda"
    echo "   Then in machine B, boot it into DRBL client mode, too. Then run"
    echo "   $ocs --source-IP 192.168.100.1 -t hda"
    echo
}
#
ask_disk_to_local_disk() {
   local available_harddisk_no ANS_TMP
   # src_dev, tgt_dev is like hda, sda...
   available_harddisk_no="$(get_harddisk_list | wc -w)"
   if [ "$available_harddisk_no" -lt 2 ]; then
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "To do local disk to disk clone, there must be at least 2 harddisks in the machine! Only $available_harddisk_no disk is found!"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo "$msg_program_stop"
      echo -n "$msg_press_enter_to_continue"
      read
      exit 1
   fi
   ANS_TMP=`mktemp /tmp/ocs_ans.XXXXXX`
   trap "[ -f "$ANS_TMP" ] && rm -f $ANS_TMP" HUP INT QUIT TERM EXIT
   get_input_dev_name $ANS_TMP harddisk radiolist yes "$msg_local_source_disk"
   # we have to remove " (comes with checklist in dialog) so that for loop
   # will work (Specially for FC3/4...)
   src_dev="$(cat $ANS_TMP | tr -d \")"
   [ -z "$src_dev" ] && exit 1
   check_input_hd $src_dev

   get_input_dev_name $ANS_TMP harddisk radiolist yes "$msg_local_target_disk" "$src_dev"
   # we have to remove " (comes with checklist in dialog) so that for loop
   # will work (Specially for FC3/4...)
   tgt_dev="$(cat $ANS_TMP | tr -d \")"
   [ -f "$ANS_TMP" ] && rm -f $ANS_TMP
   [ -z "$tgt_dev" ] && exit 1
   check_input_hd $tgt_dev
} # end of ask_disk_to_local_disk
ask_disk_to_remote_disk() {
   local ANS_TMP
   # tgt_dev is like hda, sda...
   ANS_TMP=`mktemp /tmp/ocs_ans.XXXXXX`
   trap "[ -f "$ANS_TMP" ] && rm -f $ANS_TMP" HUP INT QUIT TERM EXIT
   get_input_dev_name $ANS_TMP harddisk radiolist yes "$msg_local_source_disk"
   # we have to remove " (comes with checklist in dialog) so that for loop
   # will work (Specially for FC3/4...)
   src_dev="$(cat $ANS_TMP | tr -d \")"
   [ -f "$ANS_TMP" ] && rm -f $ANS_TMP
   [ -z "$src_dev" ] && exit 1
   check_input_hd $src_dev
}
ask_part_to_local_part() {
   local available_partition_no ANS_TMP
   #  src_dev, tgt_dev is like hda1, sda1...
   available_partition_no="$(get_partition_list | wc -w)"
   if [ "$available_partition_no" -lt 2 ]; then
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "To do local disk to disk clone, there must be at least 2 partitions in the machine! Only $available_partition_no disk is found!"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo "$msg_program_stop"
      echo -n "$msg_press_enter_to_continue"
      read
      exit 1
   fi
   ANS_TMP=`mktemp /tmp/ocs_ans.XXXXXX`
   trap "[ -f "$ANS_TMP" ] && rm -f $ANS_TMP" HUP INT QUIT TERM EXIT

   get_input_dev_name $ANS_TMP partition radiolist yes "$msg_local_source_part"
   # we have to remove " (comes with checklist in dialog) so that for loop
   # will work (Specially for FC3/4...)
   src_dev="$(cat $ANS_TMP | tr -d \")"
   [ -z "$src_dev" ] && exit 1
   check_input_partition $src_dev

   get_input_dev_name $ANS_TMP partition radiolist yes "$msg_local_target_part" "$src_dev"
   # we have to remove " (comes with checklist in dialog) so that for loop
   # will work (Specially for FC3/4...)
   tgt_dev="$(cat $ANS_TMP | tr -d \")"
   [ -f "$ANS_TMP" ] && rm -f $ANS_TMP
   [ -z "$tgt_dev" ] && exit 1
   check_input_partition $tgt_dev
} # end of ask_part_to_local_part
ask_part_to_remote_part() {
   local ANS_TMP
   # src_dev is like hda1, sda1...
   ANS_TMP=`mktemp /tmp/ocs_ans.XXXXXX`
   trap "[ -f "$ANS_TMP" ] && rm -f $ANS_TMP" HUP INT QUIT TERM EXIT
   get_input_dev_name $ANS_TMP partition radiolist yes "$msg_local_source_part"
   # we have to remove " (comes with checklist in dialog) so that for loop
   # will work (Specially for FC3/4...)
   src_dev="$(cat $ANS_TMP | tr -d \")"
   [ -f "$ANS_TMP" ] && rm -f $ANS_TMP
   [ -z "$src_dev" ] && exit 1
   check_input_partition $src_dev
} # end of ask_part_to_remote_part

#
get_onthefly_input_param() {
  local TMP ASK_OCS_ONTHEFLY_TYPE ocs_otf_type
  # (1) disk to local disk
  # (2) disk to remote disk
  # (3) partiiton to local partition
  # (4) partiiton to remote partition
  TMP="$(mktemp /tmp/ontheflymenu.XXXXXX)"
  ASK_OCS_ONTHEFLY_TYPE=1
  while [ "$ASK_OCS_ONTHEFLY_TYPE" -ne 0 ]; do
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "Clonezilla" --menu "$msg_clonezilla_is_free_and_no_warranty\n$msg_choose_mode:" \
    0 0 0 \
    disk_to_local_disk  $msg_disk_to_local_disk \
    disk_to_remote_disk $msg_disk_to_remote_disk \
    part_to_local_part $msg_part_to_local_part \
    part_to_remote_part $msg_part_to_remote_part \
    "exit"           "$msg_exit. $msg_enter_cml" \
    2> $TMP
    ocs_otf_type="$(cat $TMP)"
    if [ -z "$ocs_otf_type" ]; then
      ASK_OCS_ONTHEFLY_TYPE=1
    else
      ASK_OCS_ONTHEFLY_TYPE=0
    fi
  done
  [ -f "$TMP" ] && rm -f $TMP
  [ -z "$ocs_otf_type" ] && echo "You must specify the action! Program terminated!!!" && exit 1
  case "$ocs_otf_type" in
    disk_to_local_disk)	ask_disk_to_local_disk;;
    disk_to_remote_disk) 
                        STATUS="clone_server"
                        network_config_if_necessary
                        ask_disk_to_remote_disk;;
    part_to_local_part) ask_part_to_local_part;;
    part_to_remote_part) 
                        STATUS="clone_server"
                        network_config_if_necessary
                        ask_part_to_remote_part;;
    exit) exit 0;;
  esac
} # end of get_onthefly_input_param
set_ocs_onthefly_extra_param() {
  # This function is used to be called inside ocs-onthefly, not from other program.
  local OCS_PARAM_TMP="$(mktemp /tmp/onthefly-extramenu.XXXXXX)"
  $DIA --separate-output --backtitle "$msg_nchc_free_software_labs" --title  \
  "$msg_ocs_onthefly_advanced_extra_param" --checklist "$msg_choose_param_to_set:" \
  0 0 0 $DIA_ESC \
  "-g-auto"  "$msg_ocs_onthefly_param_g" on \
  "-e"       "$msg_ocs_onthefly_param_e" off \
  "-nogui"   "$msg_ocs_onthefly_param_nogui" off \
  "-n"       "$msg_ocs_onthefly_param_n" off \
  "-m"       "$msg_ocs_onthefly_param_m" off \
  "-o"       "$msg_ocs_onthefly_param_o" off \
  "-b"       "$msg_ocs_onthefly_param_b" off \
  "-v"       "$msg_ocs_onthefly_param_v" off \
  2> $OCS_PARAM_TMP
  # force to strip the unnecessary quotation ', this is specially for dialog (from cdialog) in Mandriva. Otherwise it will cause -p reboot become (containing space) '-p reboot', which is wrong option in dcs.
  LC_ALL=C perl -pi -e "s/\'//g" $OCS_PARAM_TMP
  # parse them
  for imode in `cat $OCS_PARAM_TMP`; do
    case "$imode" in
      -b|--batch-mode) batch_mode="on" ;;
      -g-auto)  install_grub="on";
                grub_partition="auto" ;;
      -n|--no-sfdisk) RUN_SFDISK="no" ;;
      -m|--no-boot-loader-clone) CLONE_BOOT_LOADER="no" ;;
      -e|--resize-partition) resize_partition="on" ;;
      -o|--load-geometry) load_HD_CHS="yes" ;;
      -nogui|--nogui) nogui="on" ;;
      -v|--verbose) verbose="on" ;;
      -*) echo "${0}: ${1}: invalid option" >&2
          USAGE >& 2
          exit 2 ;;
      *)  break ;;
    esac
  done
  [ -f "$OCS_PARAM_TMP" ] && rm -f $OCS_PARAM_TMP
} # end of set_ocs_onthefly_extra_param

########################
##### MAIN PROGRAM #####
########################
# Fedora Core 1 seems to use dumb for rc1, we have to force it use linux.
# otherwise setterm will complain.
[ -z "$TERM" -o "$TERM" = "dumb" ] && TERM="linux"
echo "Setting the TERM as $TERM"
export TERM="$TERM"

#
check_if_root

# PARTIMAGE_RESTORE_OPT & PARTIMAGE_SAVE_OPT will put into partimage command options
PARTIMAGE_RESTORE_OPT=
PARTIMAGE_SAVE_OPT=
STATUS=
ocs_onthefly_mode=""
# Some default setting.
batch_mode="off"
install_grub="off";
grub_partition="auto" 
RUN_SFDISK="yes" 
CLONE_BOOT_LOADER="yes" 
resize_partition="off" 
load_HD_CHS="no" 
nogui="off" 
verbose="off" 

# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -b|--batch-mode)
            shift; batch_mode="on"
	    ;;
    -l|--language)
	shift;
        if [ -z "$(echo $1 |grep ^-.)" ]; then
          # skip the -xx option, in case 
	  specified_lang="$1"
	  shift
        fi
	;;
    -g|--grub-install)  
            install_grub="on"
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              grub_partition=$1
              shift
            fi
            ;;
    -n|--no-sfdisk)
            shift; RUN_SFDISK="no"
	    ;;
    -m|--no-boot-loader-clone)
            shift; CLONE_BOOT_LOADER="no"
	    ;;
    -s|--source-IP)
            shift;
	    STATUS="clone_client"
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              SOURCE_IP=$1
            fi
            shift;;
    -f|--source)
            shift;
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              src_dev=$1
            fi
            shift;;
    -t|--target)
            shift;
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              tgt_dev=$1
            fi
            shift;;
    -p|--port)
            shift;
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              NC_PORT=$1
            fi
            shift;;
    -i|--filter)
            shift;
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
	      filter=$1
            fi
            shift;;
    -r|--server)
            shift; STATUS="clone_server"
            ;;
    -e|--resize-partition)
            resize_partition="on"
	    shift;;
    -o|--load-geometry)
	    load_HD_CHS="yes"
            shift;;
    -nogui|--nogui)
            # -nogui is for backward compatable, better to use --nogui
            nogui="on"
            shift;;
    -x|--interactive) 
	    ocs_onthefly_mode="interactive"
	    shift;;
    -v|--verbose)
	    shift; verbose="on"
            ;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            USAGE >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

ask_and_load_lang_set $specified_lang

# check DIA
check_DIA_set_ESC $DIA

# Turn off swap and LVM2, unlock the busy partitions.
turn_off_swap_and_LVM2

#
if [ "$ocs_onthefly_mode" = "interactive" ]; then
  get_onthefly_input_param
  set_ocs_onthefly_extra_param
fi
#
if [ "$nogui" = "on" ]; then
  PARTIMAGE_RESTORE_EXTRA_OPT="-B gui=no"
fi
#
if [ -n "$STATUS" ]; then
  # It's in network clone mode
  if [ "$STATUS" = "clone_server" ]; then
    [ -z "$src_dev" ] && USAGE && exit 1
  elif [ "$STATUS" = "clone_client" ]; then
    [ -z "$tgt_dev" -o -z "$SOURCE_IP" ] && USAGE && exit 1
  fi
  #
  echo "$msg_delimiter_star_line"
  mode="network"
  my_ips="$(/opt/drbl/bin/get-all-nic-ip -r)"
  echo "$msg_my_IP_in_drbl_env: $my_ips"
  [ -z "$NC_PORT" ] && NC_PORT=$NC_PORT_DEFAULT
  # The NC port for target machine to notify the server
  JOB_NOTIFY_PORT=$((NC_PORT +1))
  # Get the source port option of nc is "-p" or none.
  nc_lp_check
else
  # It's in local clone mode
  [ -z "$src_dev" -o -z "$tgt_dev" ] && USAGE && exit 1
  #
  echo "$msg_delimiter_star_line"
  mode="local"
fi

if [ "$verbose" = "on" ]; then
  echo "PARTIMAGE_RESTORE_OPT: $PARTIMAGE_RESTORE_OPT"
  echo "PARTIMAGE_SAVE_OPT: $PARTIMAGE_SAVE_OPT"
  echo "SOURCE: $src_dev"
  echo "TARGET: $tgt_dev"
  echo "PORT for netcat: $NC_PORT"
fi

#
set_filter_program

pre_checking

# check source and target type
if [ -n "$src_dev" ]; then
  check_input_param $src_dev
  ret=$?
  case "$ret" in
     3)
  	source_type="disk"
  	;;
     5)
  	source_type="partition"
  	;;
  esac
fi
if [ -n "$tgt_dev" ]; then
  check_input_param $tgt_dev
  ret=$?
  case "$ret" in
     3)
  	target_type="disk"
  	;;
     5)
  	target_type="partition"
  	;;
  esac
fi

case "$mode" in
  local)
    if [ "$source_type" != "$target_type" ]; then
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "$msg_different_type_of_input_devs ($src_dev to $tgt_dev)! $msg_program_stop!"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      exit 1
    fi
    ;;
  network)
    # clean the stalled partimage and netcat process
    kill_clone_prog_nc_process
    ;;
esac

#
if [ "$STATUS" = "clone_server" ]; then
  hd_src_tmp="$(mktemp -d /tmp/ocs_onthefly_src.XXXXXX)"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_this_is_for_source_machine."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "source_type=$source_type" > $hd_src_tmp/target_type.ocs_onthefly
  cat $hd_src_tmp/target_type.ocs_onthefly | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
  NC_PORT=$((NC_PORT + 2))
elif [ "$STATUS" = "clone_client" ]; then
  hd_tgt_tmp="$(mktemp -d /tmp/ocs_onthefly_tgt.XXXXXX)"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_this_is_for_target_machine"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  $NC_CMD $NC_CLIENT_EXTRA_OPT $SOURCE_IP $NC_PORT > $hd_tgt_tmp/target_type.ocs_onthefly
  NC_PORT=$((NC_PORT + 2))
  . $hd_tgt_tmp/target_type.ocs_onthefly
  source_type=$source_type
fi

# convert partition to disk (Ex. hda1 -> hda), even if it's partition, the sed action is still OK, i.e. won't affect if it's partition already.
[ -n "$src_dev" ] && source_hd=$(echo $src_dev | sed -e "s/[0-9]*//g")
[ -n "$tgt_dev" ] && target_hd=$(echo $tgt_dev | sed -e "s/[0-9]*//g")

# just in case
if [ "$STATUS" = "clone_server" ]; then
  if [ "$source_type" = "disk" -a -z "$source_hd" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "Source type is disk, but source disk name (Ex. hda) can NOT be found!"
    echo "$msg_program_stop!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "$msg_press_enter_to_continue"
    read
    exit 1
  fi
elif [ "$STATUS" = "clone_client" ]; then
  if [ "$target_type" = "disk" -a -z "$target_hd" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "Target type is disk, but target disk name (Ex. hdb) can NOT be found!"
    echo "$msg_program_stop!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "$msg_press_enter_to_continue"
    read
    exit 1
  fi
fi

echo "$msg_delimiter_star_line"
# turn on DMA and turn off swap/LVM.
screen_not_blank
[ -n "$target_hd" ] && turn_on_hd_dma /dev/$target_hd

echo "$msg_delimiter_star_line"

# prepare the partition table and MBR (if necessary)
case "$mode" in
  local)   prepare_local_clone_dev_info ;;
  network) prepare_network_clone_dev_info ;;
esac

# confirm first
confirm_do_it_in_target_dev

# partition table
create_partition_table_in_target

# process the boot loader
clone_boot_loader_in_target

#
echo "$msg_delimiter_star_line"
# start cloning
case "$mode" in
  local) local_dev_clone ;;
  network) clone_over_net ;;
esac

# create swap partition, resize partition, clean the temp partition table, and re-install grub
post_process_in_target_dev

if [ "$STATUS" = "clone_server" ]; then
  echo "$msg_delimiter_star_line"
  echo -n "Waiting for the target machine to connect... "
  $NC_CMD -l $NC_LOCAL_PORT_OPT $JOB_NOTIFY_PORT
  [ -d "$hd_src_tmp" ] && rm -rf $hd_src_tmp
elif [ "$STATUS" = "clone_client" ]; then
  echo "$msg_delimiter_star_line"
  echo -n "Notifying the source machine that my job is done... "
  echo 'done!' | $NC_CMD $NC_QUIT_OPT $SOURCE_IP $JOB_NOTIFY_PORT
  [ -d "$hd_tgt_tmp" ] && rm -rf $hd_tgt_tmp
  echo 'done!'
fi

exit 0
