#!/usr/bin/bash

# Creates a tarball out of content at the specified directory path.

usage() {
    cat <<EOF
Usage:
    $0 [--include-vcs] [--exclude-from FILE] path dir_name source_name

    Creates a compressed tarball out of the
    specified path content. Uses tar to do the job.

    By default, omits any VCS-specific files.

Options:
    -h, --help             Print help
    --include-vcs          Include version control system directories. By default excluded.
    --exclude-from FILE    Exclude files matching patterns listed in FILE.

Arguments:
    path                   Path to the content that should be packed.
    dir_name               Name of the directory in the created tarball.
    source_name            Name of the resulting tarball file.
EOF
}

CONTENT_PATH=""
DIR_NAME=""
SOURCE_NAME=""
EXCLUDE_VCS="--exclude-vcs"
EXCLUDE_FROM=""
EXCLUDE_FROM_FILE=""

while [ -n "$1" ] ; do
    case "$1" in
    -h|--help)
        usage
        exit 0
        ;;
    --include-vcs)
        EXCLUDE_VCS=""
        ;;
    --exclude-from)
        shift
        EXCLUDE_FROM="--exclude-from"
        EXCLUDE_FROM_FILE="$1"
        ;;
    *)
        CONTENT_PATH="$(builtin cd "$1" && pwd -P)"
        shift
        DIR_NAME="$1"
        shift
        SOURCE_NAME="$1"
        ;;
    esac
    shift
done

if [ -z "$CONTENT_PATH" ] || [ -z "$SOURCE_NAME" ] || [ -z "$DIR_NAME" ]; then
    usage
    exit -1
fi

touch "$SOURCE_NAME" # trick together with --exclude "SOURCE_NAME" below to allow creating the archive in CWD
tar caf "$SOURCE_NAME" $EXCLUDE_VCS $EXCLUDE_FROM $EXCLUDE_FROM_FILE --absolute-names --transform "s|^$CONTENT_PATH|$DIR_NAME/|" --transform "s|^$DIR_NAME//*|$DIR_NAME/|" --exclude "$SOURCE_NAME" $CONTENT_PATH
