#!/bin/bash
# shellcheck disable=SC2155
if ! type "include" > /dev/null 2>&1; then
  include() {
  . "$(cd "$(dirname "$1")" && pwd)/${2}";
  };
fi
include "${BASH_SOURCE[0]}" ../pragma_once.bash
if ! pragma_once ${BASH_SOURCE[0]}; then return 0; fi
include "${BASH_SOURCE[0]}" ./global_rely/export.bash
# shellcheck source=./global_rely/export.bash


extract(){
  local suffix=$1
  local zip_file_path=$2
  local dest_dir=$3
  case "$suffix" in
    "tar.gz" | "tgz")
      exec_record_fast_fail "tar -xzf $zip_file_path -C $dest_dir"
      ;;
    "tar.bz2" | "tbz")
      exec_record_fast_fail "tar -xjf $zip_file_path -C $dest_dir"
      ;;
    "tar.xz" | "txz")
      exec_record_fast_fail "tar -xJf $zip_file_path -C $dest_dir"
      ;;
    "zip")
      exec_record_fast_fail "unzip $zip_file_path -d $dest_dir"
      ;;
    "gz")
      exec_record_fast_fail "gunzip -c $zip_file_path > $dest_dir"
      ;;
    "bz2")
      exec_record_fast_fail "bunzip2 -c $zip_file_path > $dest_dir"
      ;;
    *)
      echo "Unsupported file format: $suffix"
      exit 124
      ;;
  esac
}


get_suffix() {
  local -n ret=$1
  local filename="$(basename "$2")"
  local reversed_filename=$(echo "$filename" | rev)
  local first_extension=$(echo "$reversed_filename" | cut -d'.' -f1 | rev)
  local second_extension=$(echo "$reversed_filename" | cut -d'.' -f2 | rev)
  if [ -z "$second_extension" ]; then
    ret=$first_extension
  else
    if [[ "$second_extension" == "tar" ]]; then
      if [[ "$first_extension" == "gz" ]]; then
        ret="tar.gz"
      elif [[ "$first_extension" == "bz2" ]]; then
        ret="tar.bz2"
      elif [[ "$first_extension" == "xz" ]]; then
        ret="tar.xz"
      else
        echo "tar but not ok  first_extension:$first_extension second_extension:$second_extension"
        exit 101;
      fi
    else
#      echo "two . but not tar  first_extension:$first_extension second_extension:$second_extension"
#      exit 102
      ret=$first_extension
    fi
  fi
}

package_xz() {
  local path=$1
  local dir_path=$(dirname ${path})
  local name=$(basename ${path})
#  echo "$path"
#  echo "$dir_path"
#  echo "$name"
  cd $dir_path
  size=$(du -sb "$name" | awk '{print $1}')
  #tar --dereference -cf - "$name" | pv -s $size | xz -T0 -3 > "$name.tar.xz"
  exec_record_fast_fail "tar --dereference -cf - \"$name\" | pv -s $size | xz -T0 -3 > \"$name.tar.xz\""
}


return 0