2
0
mirror of https://github.com/kazhala/dotbare synced 2024-11-04 06:00:45 +00:00
dotbare/scripts/fbackup
2020-05-19 17:51:13 +10:00

91 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# backup all tracked files
#
# @params
# Globals
# ${mydir}: current dir of the script
# ${backup_type}: types of backup, individual or all
# ${selected_files}: selected files to backup
# ${action_command}: actions to run, cp|mv
# Arguments
# -h: show help message and exit
# -s: select individual files through fzf and backup
# -p: pass in path and backup
# -m: use mv to backup instead of cp
set -e
set -f
mydir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "${mydir}"/../helper/set_variable.sh
source "${mydir}"/../helper/git_query.sh
function usage() {
echo -e "Usage: dotbare fbackup [-h] [-s] [-p PATH] ...\n"
echo -e "Backup files to ${DOTBARE_BACKUP}"
echo -e "This is useful when untracking files or migrating on new machines\n"
echo -e "Default: backup every tracked files using cp to ${DOTBARE_BACKUP} directory\n"
echo -e "optional arguments:"
echo -e " -h\t\tshow this help message and exit"
echo -e " -s\t\tselect individual file through fzf and backup"
echo -e " -p PATH\tsepcify path to backup"
echo -e " -m\t\tuse mv command for backup instead of default cp"
}
#######################################
# backup passed in files while preserving directory info
# Arguments:
# $1: files to backup, seperate by \n
# $2: action command (cp|mv)
#######################################
function dotbare_backup() {
local selected_files="$1"
local action_command="${2:-cp}"
while IFS= read -r line; do
dir_name=$(dirname "${line}")
[[ ! -d "${DOTBARE_BACKUP}/${dir_name}" ]] && mkdir -p "${DOTBARE_BACKUP}/${dir_name}"
command "${action_command}" -v "${line}" "${DOTBARE_BACKUP}/${line}"
done <<< "${selected_files}"
exit 0
}
backup_type="all"
action_command='cp'
while getopts ":hsp:m" opt; do
case "$opt" in
s)
backup_type='individual'
;;
p)
selected_files="${OPTARG}"
;;
m)
action_command="mv"
;;
h)
usage
exit 0
;;
*)
echo "Invalid option: ${OPTARG}" >&2
usage
exit 1
;;
esac
done
[[ -n "${selected_files}" ]] && dotbare_backup "${selected_files}" "${action_command}"
cd "${DOTBARE_TREE}"
if [[ "${backup_type}" == 'individual' ]]; then
selected_files=$(get_git_file "select files to backup" "raw")
else
selected_files=$(/usr/bin/git --git-dir="${DOTBARE_DIR}" --work-tree="${DOTBARE_TREE}" \
ls-files --full-name --directory "${DOTBARE_TREE}")
fi
[[ -z "${selected_files}" ]] && exit 1
dotbare_backup "${selected_files}" "${action_command}"