#!/bin/bash

if [ "$#" -lt 2 ]; then
    echo "Usage: $0 [-v/--verbose] [-c/--compress | -d/--decompress] <directory_or_file>"
    exit 1
fi

VERBOSE=false
ACTION=""

if [[ "$1" == "-v" || "$1" == "--verbose" ]]; then
    VERBOSE=true
    shift
fi

if [[ "$1" == "-c" || "$1" == "--compress" ]]; then
    ACTION="compress"
elif [[ "$1" == "-d" || "$1" == "--decompress" ]]; then
    ACTION="decompress"
else
    echo "Error: Action must be '-c|--compress' or '-d|--decompress'."
    exit 1
fi

TARGET="$2"
TARGET=$(echo "$TARGET" | sed 's/[[:space:]]\+$//; s/[\/]*$//')

if [ -d "$TARGET" ]; then
    TARGETS="Directory"
elif [ -f "$TARGET" ]; then
    TARGETS="File"
else
    echo "Error: '$TARGET' is not a valid file or directory."
    exit 1
fi

if [ "$VERBOSE" = true ]; then
    TAR_COMP_OPTIONS="-cvf"
    TAR_DEC_OPTIONS="-xvf"
else
    TAR_COMP_OPTIONS="-cf"
    TAR_DEC_OPTIONS="-xf"
fi

case "$ACTION" in
    compress)
        [ "$VERBOSE" = true ] && echo "Compressing '$TARGET' to '$TARGET.tar.zst'."
        tar -I "zstd -T$(nproc)" $TAR_COMP_OPTIONS "$TARGET.tar.zst" "$TARGET"
        [ "$VERBOSE" = true ] && echo ""
        echo "$TARGETS '$TARGET' has been compressed to '$TARGET.tar.zst'."
        ;;
    decompress)
        [ "$VERBOSE" = true ] && echo "Decompressing '$TARGET'"
        tar -I "zstd -T$(nproc)" $TAR_DEC_OPTIONS "$TARGET"
        [ "$VERBOSE" = true ] && echo ""
        echo "Archive '$TARGET' has been decompressed."
        ;;
    *)
        exit 1
esac
