# Convert between different formats.
# Usage: convert <FROM.gz> <TO.xz>
convert() {
  local input="${1}"
  local output="${2}"
  local from="${input##*.}"
  local to="${output##*.}"

  # Report no output.
  if [[ "${to}" = "" ]]; then
    echo -e "${color_bred}no output file/format.${color_default}"
    return 1
  fi

  # Report no input.
  if [[ "${from}" = "" ]]; then
    echo -e "${color_bred}no input file/format.${color_default}"
    return 2
  fi

  # Process.
  case "${from}-${to}" in
    "gz-xz"|"tgz-txz")
      _convert_gz-xz "${input}" "${output}"
      ;;
    "xz-gz"|"txz-tgz")
      _convert_xz-gz "${input}" "${output}"
      ;;
    *)
      echo -e "${color_yellow}Conversion ${from}-${to} not supported.${color_default}"
      return 3
      ;;
  esac

  if [[ $? = 0 ]]; then
    echo -e "${color_green}Done.${color_default}"
  else
    echo -e "${color_bred}There were errors.${color_default}"
  fi
}

_convert_gz-xz() {
  pv "${1}" | gzip -d | xz -9e > "${2}"
}

_convert_xz-gz() {
  pv "${1}" | xz -d | gzip -1 > "${2}"
}

# Export.
export -f convert _convert_gz-xz _convert_xz-gz