#!/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:
# (partimage -z0 -o -d --volume=0 -B gui=no save /dev/hda1 stdout |
#  partimage -M -f3 -b restore /dev/hdc1 stdin)
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 basic functions of ocs
. /opt/drbl/sbin/ocs-functions

# 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 "$msg_press_enter_to_continue"
        read
        exit 1
  esac
  return $recode
} # end of check_input_param
#
check_pt_then_run_sfdisk() {
  echo -n "$msg_creating_partition_in_target"
  if [ -f "$pt_tmp" ]; then
    echo "$msg_partition_table_for_target_dev \"$target_hd\":"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "-------------------------------------------------------------"
    cat $pt_tmp
    echo "-------------------------------------------------------------"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    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
    case "$fdisk_ans" in
      n|N|[nN][oO])
             echo "$msg_ok_we_will_keep_old_partition_table"
             ;;
      *)
             sfdisk --force $sfdisk_opt /dev/$target_hd < $pt_tmp
             ;;
    esac
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "$msg_fail_to_create_partition_table_in_target_dev: /dev/$target_p! $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

  $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
  [ -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_partimage_nc_process() {
  echo "Terminate partimage and $NC_CMD processs if they exist..."
  pkill -u root partimage
  pkill -u root $NC_CMD
} # end of kill_partimage_nc_process

# 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

#
USAGE() {
    echo "Usage:"
    echo "To run clonezilla on-the-fly:"
    echo "$ocs [OPTION]"
    echo "Option"
    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 gzip. Use \"cat\" if you do not want to compress (Good for fast internode network)."
    echo "-n, --no-sfdisk          skip partition table creation"
    echo "-m, --no-mbr-clone       do NOT clone MBR"
    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 "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
}

# PARTIMAGE_RESTORE_OPT & PARTIMAGE_SAVE_OPT will put into partimage command options
PARTIMAGE_RESTORE_OPT=
PARTIMAGE_SAVE_OPT=
STATUS=
load_HD_CHS=

# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -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-mbr-clone)
            shift; CLONE_MBR="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 
              source_p=$1
            fi
            shift;;
    -t|--target)
            shift;
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              target_p=$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;;
    -v|--verbose)
	    shift; verbose="on"
            ;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            USAGE >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

#
if [ -n "$STATUS" ]; then
  # It's in network clone mode
  if [ "$STATUS" = "clone_server" ]; then
    [ -z "$source_p" ] && USAGE && exit 1
  elif [ "$STATUS" = "clone_client" ]; then
    [ -z "$target_p" -o -z "$SOURCE_IP" ] && USAGE && exit 1
  fi
  #
  ask_and_load_lang_set $specified_lang
  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 "$source_p" -o -z "$target_p" ] && USAGE && exit 1
  #
  ask_and_load_lang_set $specified_lang
  echo "$msg_delimiter_star_line"
  mode="local"
fi

case "$filter" in
  lzop)
       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
       ;;
  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 gzip &>/dev/null; then
         filter_comp="gzip -c"
         filter_decomp="gzip -cd"
       else
         [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
         echo "gzip is NOT found! Program terminated!!!"
         [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	 exit 1
       fi
       ;;
esac


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

# check if it runs in DRBL server, if yes, warn user!
if [ -d /tftpboot/nbi_img/ ]; 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 "$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 echo $target_p | grep -q $source_p; then
    echo "$msg_src_target_r_same_dev $msg_program_stop"
    exit 1
  fi
fi

# check source and target type
if [ -n "$source_p" ]; then
  check_input_param $source_p
  ret=$?
  case "$ret" in
     3)
  	source_type="disk"
  	;;
     5)
  	source_type="partition"
  	;;
  esac
fi
if [ -n "$target_p" ]; then
  check_input_param $target_p
  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 ($source_p to $target_p)! $msg_program_stop!"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      exit 1
    fi
    ;;
  network)
    # clean the stalled partimage and netcat process
    kill_partimage_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 $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

# create the partitions if necessary.
[ -n "$source_p" ] && src_hd=$(echo $source_p | sed -e "s/[0-9]*//g")
[ -n "$target_p" ] && target_hd=$(echo $target_p | sed -e "s/[0-9]*//g")

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

# swapoff -a, just in case
if [ -e /etc/debian_version -o -e /etc/SuSE-release ]; then
  # Debian
  # just stop it!
  /etc/init.d/mkswapfile stop
else
  # RH-like
  [ -f /var/lock/subsys/mkswapfile ] && /etc/init.d/mkswapfile stop
fi
/sbin/swapoff -a
# Stop LVM so that the HD will not be occupied, we use script comes from
# gentoo, but actually just run "vgchange -an" will be ok.
$DRBL_SCRIPT_PATH/sbin/lvm2-stop.sh

# prepare the partition table and MBR (if necessary)
if [ "$mode" = "local" ]; then
  pt_tmp=$(mktemp /tmp/pt.XXXXXX)
  sfdisk -d /dev/$src_hd > $pt_tmp
  # change the dev to target in the $pt_tmp
  #perl -p -i -e "s|/dev/$src_hd|/dev/$target_hd|g" $pt_tmp
  perl -p -i -e "s|/dev/[hs]d[a-z]|/dev/$target_hd|g" $pt_tmp
  ret_pt_sf=$?
elif [ "$mode" = "network" ]; then
  if [ "$STATUS" = "clone_server" ]; then
    pt_tmp=$hd_src_tmp/pt.sf
    # partition table
    sfdisk -d /dev/$src_hd > $pt_tmp
    output_HD_CHS $src_hd $hd_src_tmp/
    # MBR
    dd if=/dev/$source_p of=$hd_src_tmp/mbr count=1 bs=512 &> /dev/null
    cat $hd_src_tmp/pt.sf | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
    NC_PORT=$((NC_PORT + 2))
    cat $hd_src_tmp/chs.sf | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
    NC_PORT=$((NC_PORT + 2))
    cat $hd_src_tmp/mbr | $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
    # partition table
    pt_tmp=$hd_tgt_tmp/pt.sf
    $NC_CMD $SOURCE_IP $NC_PORT > $pt_tmp
    NC_PORT=$((NC_PORT + 2))
    # CHS
    $NC_CMD $SOURCE_IP $NC_PORT > $hd_tgt_tmp/chs.sf
    NC_PORT=$((NC_PORT + 2))
    # get sfdisk_opt if load_HD_CHS is yes
    [ "$load_HD_CHS" = "yes" ] && load_HD_geometry $hd_tgt_tmp/
    # MBR
    $NC_CMD $SOURCE_IP $NC_PORT > $hd_tgt_tmp/mbr
    NC_PORT=$((NC_PORT + 2))
    # change the dev to target in the $pt_tmp
    perl -p -i -e "s|/dev/[hs]d[a-z]|/dev/$target_hd|g" $pt_tmp
  fi
fi

# process the MBR
echo "$msg_delimiter_star_line"
if [ "$CLONE_MBR" != "no" ] && [ "$source_type" = "disk" ] && [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then
  echo "$msg_do_you_want_to_clone_the_MBR_to: $target_p ?"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "[Y/n] "
  read mbr_ans
  case "$mbr_ans" in
    n|N|[nN][oO])
       echo "OK, $msg_skip_clone_MBR."
       ;;
    *)
       if [ "$mode" = "local" ]; then
         echo "Cloning the MBR from \"$src_hd\" to \"$target_hd\"..."
         dd if=/dev/$source_p of=/dev/$target_p count=1 bs=512 &> /dev/null
         ret=$?
       elif [ "$STATUS" = "clone_client" ]; then
         echo "Cloning the MBR from that in $SOURCE_IP to \"$target_hd\"..."
         dd if=$hd_tgt_tmp/mbr of=/dev/$target_p count=1 bs=512 &> /dev/null
         ret=$?
       fi
       if [ "$ret" -ge 1 ]; then
         [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
         echo "$msg_failed_to_clone_the_MBR: \"$target_hd\"!!!"
         echo "$msg_program_stop!!"
         [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
         exit 1
       fi
       ;;
  esac
fi
#
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 "$(fdisk -l /dev/$target_hd |grep -E "/dev/[sh]d[a-z][0-9]+")" ] ; then
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "$msg_a_partition_table_already_exist: \"$target_hd\""
      echo "$msg_do_u_want_to_duplicate_the_partiton_layout_to: \"$target_hd\" ?"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo -n "[y/N] "
      read fdisk_anyway
      case "$fdisk_anyway" in
         [yY]|[yY][eE][sS])
              fdisk_target="yes"
              ;;
         *)
              fdisk_target="no"
              ;;
      esac
    else
      fdisk_target="yes"
    fi
    
    # partition table
    if [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then
      [ "$fdisk_target" = "yes" ] && check_pt_then_run_sfdisk
    fi
  fi
fi

#
echo "$msg_delimiter_star_line"
# start cloning
if [ "$mode" = "local" ]; then
  case "$source_type" in
    partition)
       echo "Cloning the $source_p to $target_p..."
       partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save /dev/$source_p stdout 2> /dev/null | \
       partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT restore /dev/$target_p stdin
       ret=$?
       if [ "$ret" -ge 1 ]; then
          echo "Failed to clone /dev/$source_p to /dev/$target_p!!!"
          echo "$msg_program_stop!!"
          exit 1
       fi
       ;;
    disk)
       for target_part in `get_known_partition $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/$src_hd/g" )
         echo "Cloning the $src_part to $target_part..."
         /sbin/checkInodeForDevice /dev/$target_part 
         partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save /dev/$src_part stdout 2> /dev/null | \
         partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT restore /dev/$target_part stdin
         ret=$?
         if [ "$ret" -ge 1 ]; then
            [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  	    echo "Failed to clone /dev/$src_part to /dev/$target_part!!!"
  	    echo "$msg_program_stop!!"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  	  exit 1
         fi
       done
       ;;
  esac
elif [ "$mode" = "network" ]; then
  # try to get the client's type
  case "$source_type" in
    partition)
       if [ "$STATUS" = "clone_server" ]; then
         echo "Running the clone server for $source_p in port $NC_PORT..."
         partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save /dev/$source_p stdout 2> /dev/null | \
         $filter_comp | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
       elif [ "$STATUS" = "clone_client" ]; then
         echo "Restoring $target_p from $SOURCE_IP:$NC_PORT..."
         $NC_CMD $SOURCE_IP $NC_PORT | $filter_decomp | \
         partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT restore /dev/$target_p stdin
         ret=$?
         if [ "$ret" -ge 1 ]; then
            echo "Failed to clone remote image to /dev/$target_p!!!"
            echo "$msg_program_stop!!"
            exit 1
         fi
       fi
       ;;
    disk)
       for target_part in `get_known_partition $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/$src_hd/g" )
         if [ "$STATUS" = "clone_server" ]; then
           echo "Feeding partition $src_part in listen mode with port $NC_PORT..."
           partimage $DEFAULT_STDOUT_PARTIMAGE_SAVE_OPT save /dev/$src_part stdout 2> /dev/null | \
           $filter_comp | $NC_CMD -l $NC_LOCAL_PORT_OPT $NC_PORT &
         elif [ "$STATUS" = "clone_client" ]; then
           echo "Restoring $target_part from $SOURCE_IP:$NC_PORT..."
           /sbin/checkInodeForDevice /dev/$target_part 
           $NC_CMD $SOURCE_IP $NC_PORT | $filter_decomp | \
           partimage $DEFAULT_STDIN_PARTIMAGE_RESTORE_OPT restore /dev/$target_part stdin
           ret=$?
           if [ "$ret" -ge 1 ]; then
              [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  	      echo "Failed to clone remote image to /dev/$target_part!!!"
  	      echo "$msg_program_stop!!"
              [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  	    exit 1
           fi
         fi
	 # use the next port to avoid being occupied.
	 NC_PORT=$((NC_PORT + 2))
       done
       ;;
  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 $filter_opt --source-IP $my_ips -t [TARGET_DEV] (TARGET_DEV is like hda, hdb, hda1, hdb1...)"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
fi

# create swap partiton, clean the temp partition table, and re-install grub
if [ "$mode" = "local" -o "$STATUS" = "clone_client" ]; then
  echo "$msg_delimiter_star_line"
  [ "$resize_partition" = "on" ] && resize_partition $target_hd
  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 "Creating the swap partition $partition..."
    mkswap /dev/$partition
  done
  echo "$msg_delimiter_star_line"
  # clean the tmp file
  [ -f "$pt_tmp" ] && rm -f $pt_tmp
  [ "$install_grub" = "on" ] && install_grub_hd $grub_partition
  echo "$msg_delimiter_star_line"
fi

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
