#!/bin/bash
#
# Copyright (C) 2026 Eugene 'Vindex' Stulin
# Distributed under the Boost Software License 1.0.

set -eu -o pipefail


# The function prints the help message.
Print_Help() {
cat <<EndOfHelp
The script packs files into a single archive.

Usage:
    ${0##*/} <format-flag> <result> <files>

Format flags:
  --tar      - create a TAR archive;
  --tar-xz   - create a TAR.XZ archive;
  --tar-gz   - create a TAR.GZ archive;
  --7z       - create a 7Z archive;
  --zip      - create a ZIP archive.

Example:
    ${0##*/} --tar-xz project.tar.xz Makefile main.c
Creates the archive "project.tar.xz" containing "Makefile" and "main.c".

Help and version:
    ${0##*/} --help|-h
    ${0##*/} --version|-v
EndOfHelp
}


# The function prints the script version.
Print_Version() {
    local VERSION_SCRIPT="$(dirname -- "${BASH_SOURCE[0]}")/bbsi-version"
    if [[ ! -x "$VERSION_SCRIPT" ]]; then
        echo "Unknown version."
    else
        "$VERSION_SCRIPT"
    fi
}


# The function prints usage error message to stderr.
Incorrect_Usage() {
    echo "Incorrect usage. See: ${0##*/} --help" >&2
}


if [[ $# -eq 0 ]]; then
    Incorrect_Usage
    exit 1
elif [[ $# -eq 1 ]]; then
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        Print_Help
        exit 0
    elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
        Print_Version
        exit 0
    else
        Incorrect_Usage
        exit 1
    fi
fi


ARCHIVE_TYPE="$1"
shift
RESULT="$1"
shift
if [[ $# -eq 0 ]]; then
    Incorrect_Usage
    exit 1
fi


if [[ -f "$RESULT" ]]; then
    ANSWER=n
    echo "This file exists: $RESULT"
    echo -n "Delete it? Y/n >: "
    read ANSWER
    ANSWER=${ANSWER,,}  # to lower case
    if [[ $ANSWER == "y" || $ANSWER == "yes" || $ANSWER == "" ]]; then
        rm -f "$RESULT"
    else
        echo "Operation canceled."
        exit 0
    fi
fi


case "$ARCHIVE_TYPE" in
    '--tar')
        tar cvf "$RESULT" "$@"
        ;;
    '--tar-xz')
        tar cvfJ "$RESULT" "$@"
        ;;
    '--tar-gz')
        tar cvfz "$RESULT" "$@"
        ;;
    '--7z')
        7z a "$RESULT" "$@"
        ;;
    '--zip')
        zip -r "$RESULT" "$@"
        ;;
    *)
        echo "Unknown archive type: $ARCHIVE_TYPE." >&2
        exit 1
esac
