#!/bin/bash

# Usage: comp <folder_to_compress> [output_fildename]

# Check if input folder is provided

VERSION="__VERSION__"

if [[ -z "$1" ]]; then
    echo "Usage:	comp <folder_or_file_to_compress> [output_file]"
    echo "comp <options>"
    exit 1
    elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
    echo "Usage:"
    echo "	comp <folder_or_file_to_compress> [output_file]"
    echo "	comp <option>"
    echo ""
    echo "Options:"
    echo "    -h	--help:		Print's this message"
    echo "    -v	--version:	Ptints the current version"
    exit 0
elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
    echo "comp version: $VERSION"
    exit 0
elif [[ ! -d "$1" || ! -f "$1" ]]; then
    echo "Invalid argument '$1'"
    echo "Usage:"
    echo "	comp <folder_to_compress> [output_file]"
    echo "	comp <option>"
    exit 1
fi

INPUT_FOLDER="$1"


# Remove trailing slash from folder name if present
INPUT_FOLDER="${INPUT_FOLDER%/}"

# Determine output filename
if [[ -n "$2" ]]; then
    OUTPUT_FILE="$2"
else
    OUTPUT_FILE="${INPUT_FOLDER}.tgz"
fi

# Check if input is a valid directory
if [[ ! -d "${INPUT_FOLDER}" ]]; then
    echo "Error: '${INPUT_FOLDER}' is not a valid directory"
    exit 1
fi

# Get total zie in bytes for progress bar
TOTAL_SIZE=$(du -sb "${INPUT_FOLDER}" | awk '{print $1}')

# Run compression with progress bar
echo "Compressing '${INPUT_FOLDER}' to ' ${OUTPUT_FILE}'..."
tar -cf - "${INPUT_FOLDER}" | pv -s "${TOTAL_SIZE}" | pigz > "${OUTPUT_FILE}"

echo "Done!"
