#!/bin/bash
#--- Test_FDisk_Cntl.sh -----------------------

# see: https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo
# and: https://www.in-ulm.de/~mascheck/various/echo+printf/



myTestFunc()
{
    local fdisk_version=2.27
    local partitions=1

    local startfrom=10
    local lastsector=25
#   local secondpartition=36

#-----------------------------------------------------------------
# compute original fdisk cntl_str's as validation referance

    ( echo d;  echo n;                    echo p;  echo ;  echo $startfrom;  echo $lastsector ;  echo w; ) | cat
    echo "--------"

    (echo d;  echo $partitions;  echo n;  echo p;  echo ;  echo $startfrom;  echo $lastsector ;  echo w; ) | cat    
    echo "--------"

    ( echo n;  echo p;  echo ;       echo $(( $lastsector + 1 ));   echo $secondpartition ;      echo w; ) | cat 

    echo "********"

#-----------------------------------------------------------------

#      cleanUp of fdisk control logic using printf instead of echo, by P.L.
# see: https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo
# caution: be aware that bash printf brain damage often removes trailing /n's 
#          this bug has been worked around in the FDisk control stream code bellow.   

	
    if [[ $partitions == 1 ]] && awk "BEGIN{exit ! ($fdisk_version >= 2.27 )}"; then
        # util-linux 2.27+ workaround for just 1 partition: prevent extra command" to fdisk.
        # # https://github.com/igorpecovnik/lib/issues/353#issuecomment-224728506
        cntl_str=$( printf "d" )               # case:1
    else
        cntl_str=$( printf "d\n%d" $partitions ) # case:2
    fi 

    cntl_str+=$(    printf "\nn\np\n\n%d\n%d\nw"     $startfrom          $lastsector      )                               

    [[ -n $secondpartition ]] && \
        cntl_str=$( printf   "n\np\n\n%d\n%d\nw" $(( $lastsector + 1 ))  $secondpartition )  # case:3               

#   ( printf "%s\n" "$cntl_str" | fdisk $rootdevicepath ) >>${Log} 2>&1  # do the fdisk thing!
    ( printf "%s\n" "$cntl_str" | cat                   )                # do the fake  thing for testing.

#------------------------------------------------------------------
    echo "********"
}



myTestFunc


#--- end of Test_FDisk_Cntl.sh ----------------
