ambevar-dotfiles/.scripts/archive

100 lines
2.4 KiB
Bash
Executable File

#!/bin/sh
_printhelp()
{
cat <<EOF
Usage: ${1##*/} [-m METHOD] [-v] FILES|FOLDERS
Create an archive from a single or multiples files/folders. The archive is
created without owner/group information.
-h: Display this help.
-m: Choose compression method.
* gz: gzip (default).
* xz: LZMA.
-v: Exclude VCS data. (GNU tar only.)
EOF
}
OPTION_VCS=""
OPTION_METHOD=""
OPTIONS="--owner=root --group=root --numeric-owner"
while getopts ":hm:v" opt; do
case $opt in
h)
_printhelp "$0"
exit 1
;;
m)
OPTION_METHOD="${OPTARG}"
;;
v)
OPTION_VCS="--exclude-vcs"
;;
?)
_printhelp "$0"
exit 1
;;
:)
echo "Missing argument."
_printhelp "$0"
exit 1
;;
esac
done
ARCEXT="tar.gz"
ARCOPT="z"
case $OPTION_METHOD in
"gz")
ARCEXT="tar.gz"
ARCOPT="z"
;;
"xz")
ARCEXT="tar.xz"
ARCOPT="J"
;;
esac
shift $(($OPTIND - 1))
## Case 1: no argument, we archive current folder to parent folder.
if [ $# -eq 0 ]; then
FULLPATH="$PWD"
OUTPUT="${FULLPATH}-$(date +%F-%H%M%S).${ARCEXT}"
(cd "${FULLPATH}/.." && \
echo "tar ${OPTION_VCS} ${OPTIONS} -${ARCOPT} -cf '$OUTPUT' '${FULLPATH##*/}'" && \
tar ${OPTION_VCS} ${OPTIONS} -${ARCOPT} -cf "$OUTPUT" "${FULLPATH##*/}" )
exit
fi
## Case 2: files and folders are passed as arguments. Each of them will be at
## the archive root. Archive is produced in current folder if it is not directly
## part of the archive.
OUTPATH="$PWD"
if [ $# -eq 1 ]; then
REALPATH="$(realpath "$1")"
OUTFILE="${REALPATH##*/}-$(date +%F-%H%M%S).${ARCEXT}"
else
OUTFILE="${PWD##*/}-$(date +%F-%H%M%S).${ARCEXT}"
fi
for i; do
REALPATH="$(realpath "$i")"
# Check if one if the argument is current folder. We need to make sure the
# archive is not created in an input folder, otherwise it will include itself.
if [ "$REALPATH" = "$(realpath "$PWD")" ]; then
OUTPATH="$(realpath "$PWD/..")"
echo "Creating archive in [$OUTPATH]."
fi
DIRNAME="${REALPATH%/*}"
BASENAME="${REALPATH##*/}"
INPUTARGS="$INPUTARGS -C '$DIRNAME' '$BASENAME'"
done
echo "tar ${OPTION_VCS} ${OPTIONS} -${ARCOPT} -cf '$OUTPATH/$OUTFILE' ${INPUTARGS}"
eval "tar ${OPTION_VCS} ${OPTIONS} -${ARCOPT} -cf '$OUTPATH/$OUTFILE' ${INPUTARGS}"