#!/usr/bin/env bash
#clear
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'
#set -x

#echo "starting: $0 <LOG_LEVEL=$1>"

### new.method

disk.usage()
{
  local this=${0##*/}
  echo "You started" 
  echo "$0

  Usage:
  $this: command   description and Parameter

      usage     prints this dialog while it will print the status when there are no parameters          
      v         print version information
      init      initializes ...nothing yet

      space.usage     lists and sums used disk space for number of <levels>
      space.free      show free space on the mounted volumes
  
  Examples
    $this v
    $this init

    $this image disk1 
  "
}

disk.space.used() { # <?depthLevel:2> # calculates the space used in this directory
# use "disk list.result.bySize" to see a sorted barchart
  local level="$1"
  shift
  if [ -z "$level" ]; then
    level=2
  fi
  if ! this.isNumber $level; then
      warn.log "level is not a number: $level"
      level=2
      silent.log "fixing level to 2"
  fi
  capture.log du -chd $level 
  RETURN="$1"
}

disk.space.free() { # # lists the free space on the mounted filesystems 
  df -h
}

disk.find() {  # <?findArguments> # finds files in the subdirectories here matching <findArguments> 
  find . "$*"
}

disk.find.completion.pattern() {
  echo -e "'-type f'\\n'-type d'\\n'-name '"
}

disk.find.dir() {  # <?name> # finds directories in the subdirectories here matching <name> 
  find . -type d -name "$1"
}

disk.find.file() { # <?name> # finds files in the subdirectories here matching <name> 
  find . -type f -name "$1"
}


disk.list.result.bySize() { #  # prints the last disk space.used calculation as bar chart
  #cat $CONFIG_PATH/result.txt | sort -hr | awk '{printf "%-10s %40s %.*s\n",$1,$2,$1,"▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄"}'
  cat $CONFIG_PATH/result.txt | sort -hr | awk '{printf "%-10s %40s %.*s\n",$1,$2,$1,"◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼◼"}'
}

disk.list.result() { #  # prints the last disk space.used calculation 
  cat $CONFIG_PATH/result.txt 
}

disk.calc() { # <mathExpression> # calculates the expression
  echo $(($*))
}

disk.calc.bytes.from.tb() { # <number> # converts terabytes to bytes
  echo $(($1*1024*1024*1024*1024))
}

disk.calc.bytes.from.gb() { # <number> # converts gigabytes to bytes
  echo $(($1*1024*1024*1024))
}

disk.calc.bytes.from.mb() { # <number> # converts megabytes to bytes
  echo $(($1*1024*1024))
}

disk.calc.bytes.from.kb() { # <number> # converts kilobytes to bytes
  echo $(($1*1024))
}

disk.calc.bytes.to.tb() { # <number> # converts bytes to terabytes
  echo "$(($1/1024/1024/1024/1024)) TB"
}

disk.calc.bytes.to.gb() { # <number> # converts bytes to gigabytes
  echo "$(($1/1024/1024/1024)) GB"
}

disk.calc.bytes.to.mb() { # <number> # converts bytes to megabytes
  echo "$(($1/1024/1024)) MB"
}

disk.calc.bytes.to.kb() { # <number> # converts bytes to kilobytes
  echo "$(($1/1024)) KB"
}

disk.list() { #  # os independant listing of attached disks
  if os.check disk.list; then
    $RESULT "$@"
  else
    important.log "$RESULT is not supported"
  fi  
}

disk.list.darwin() { #  # darwin OS listing of attached disks
  diskutil list
}

disk.list.linux() { #  # linux OS listing of attached disks
  $SUDO lsblk -e7
}

disk.list.byUUID() { #  # darwin OS listing of attached disks
  $SUDO ls -lha /dev/disk/by-uuid/
}

disk.list.by() { # <listOption> # darwin OS listing of attached disks
  $SUDO ls -lha /dev/disk/by-$1
}

disk.parameter.completion.listOption() # #
{
  c2 folders.completion /dev/disk/ | line replace "\/dev\/disk\/by-"
}

disk.eject() { #  # OS independant unmount of disks
  if os.check disk.eject; then
    $RESULT  "$@"
  else
    important.log "$RESULT is not supported"
  fi  
}

disk.get() { #  # os independant listing of attached disks
  if os.check disk.get; then
    $RESULT "$@"
  else
    important.log "$RESULT is not supported"
  fi  
}

disk.get.linux() # #
{
  local disk="$1"
  if [ -n "$1" ]; then
    shift
  fi
  blkid \
  | line split " " \
  | line replace.sedquoted '/dev' '--- DEVICE=/dev' \
  | line split '--- ' #\
  #| line find "$disk" "^$"
}

disk.name2device() # # if first parameter is empty it reads fro  std input and converts the name into a device path 
{
  local name="$1"
  if [ -n "$1" ]; then
    shift
  else
    name=$( cat - )
  fi
  echo "$name" \
  | line replace.sedquoted "-" "/" \
  | line replace.sedquoted "^" "/dev/" 
}


disk.discover() { #  # os independant listing of attached disks
  if os.check disk.discover; then
    $RESULT "$@"
  else
    important.log "$RESULT is not supported"
  fi  
}

disk.discover.linux() # #
{
  local disk="$1"
  if [ -n "$1" ]; then
    shift
  fi
  # blkid \
  # | line split " " \
  # | line replace.sedquoted '/dev' '--- DEVICE=/dev' \
  # | line split '--- '

  lsblk --noheadings -o NAME,MOUNTPOINT \
  | line find "^[ ]*└[^ ]* $" \
  | line replace "[ ]*└─"

}

disk.automount() # #
{
  disk.discover \
  | xargs disk.name2device \
  | xargs udisksctl mount -b
}

disk.automount.create.config() # #
{
  {
    echo "[Unit]"
    echo "Description=Automounted $device"
    echo ""
    echo "[Mount]"
    echo "What=$device"
    echo "Where=/media/pi/"
    echo "Type=ext4"
    echo "Options=defaults"
    echo ""
    echo "[Install]"
    echo "WantedBy=multi-user.target"
  } >/etc/systemd/system/media-pi-$UUID.mount
}

disk.eject.darwin() {
  local disk="$1"
  if [ -n "$1" ]; then
    shift
  fi

  if [ -n "$disk" ]; then
    diskutil unmountDisk /dev/$disk
  else
    private.disk.args.error.disk
  fi
}

private.disk.args.error.disk() {
    error.log "no disk specified."
    disk.list
    important.log "just specify the disk name: if /dev/disk1 is listed do: disk eject disk1"
}

disk.image() { # <disk> <imageFile:./$disk.img.gz>  # create a disk image with progress bar
  if os.check disk.image; then
    $RESULT  "$@"
  else
    important.log "$RESULT is not supported"
  fi  
}

disk.image.darwin() {
  disk.image.linux "$@"
}

disk.image.linux() {
  local disk="$1"
  if [ -n "$1" ]; then
    shift
  else
    private.disk.args.error.disk
    return 2
  fi
  local imageFile="$1"
  if [ -n "$1" ]; then
    shift
  else 
    imageFile="./$disk.img.gz"
  fi

  # if [ "$user" = "root" ]; then
  #   SUDO=""
  # else
  #   SUDO="sudo "
  # fi

  #$SUDO dd if="/disk/r${disk}" bs=1m status=progress | gzip >$imageFile
  $SUDO pv -tpreb "/dev/r${disk}" | dd bs=128m  | gzip >$imageFile
  
  #sudo echo "starting"
  #($SUDO pv -n "/dev/r${disk}" | dd of="$imageFile" bs=128M conv=notrunc,noerror) 2>&1 | dialog --gauge "Cloning disk /dev/r${disk} to , please wait..." 10 70 0

}

disk.restore.linux() { # <disk> <imageFile:./$disk.img.gz>  # restore a disk imageFile with progress bar
  local disk="$1"
  if [ -n "$1" ]; then
    shift
  else
    private.disk.args.error.disk
    return 2
  fi

  local imageFile="$1"
  if [ -n "$1" ]; then
    shift
  else 
    imageFile="./$disk.img.gz"
  fi


  # if [ "$user" = "root" ]; then
  #   SUDO=""
  # else
  #   SUDO="sudo "
  # fi

  disk.eject ${disk}
  sudo echo "starting..."
  #$SUDO dd if="/disk/r${disk}" bs=1m status=progress | gzip >$imageFile
  $SUDO   pv -tpreb "$imageFile" | gzip -dc | $SUDO dd of=/dev/r${disk} bs=128m conv=notrunc,noerror
  

  #($SUDO pv -n "/dev/r${disk}" | dd of="$imageFile" bs=128M conv=notrunc,noerror) 2>&1 | dialog --gauge "Cloning disk /dev/r${disk} to , please wait..." 10 70 0

}

disk.install.raid.support() { # # install all the necessary packeges for managing RAID and Virtual Partitions
  oo cmd mdadm
  oo cmd lvm2
  important.log "Please Reboot before you continue...."
}

disk.install.samba.support() { # # install all the necessary packeges for managing RAID and Virtual Partitions
  install samba.support
}

disk.start() # <method> <parameter> # default start and parameter processing
{
  #echo "sourcing init"
  source this
  source os

  # if [ -z "$1" ]; then
  #   status.discover "$@"
  #   return 0
  # fi

  this.start "$@"
}

disk.start "$@"

