sync-dot-files/sync-dot-files.sh

78 lines
2.2 KiB
Bash
Raw Permalink Normal View History

2023-03-16 23:48:55 +01:00
#!/bin/bash
declare ssh_key
ssh_key="${1:?}"
declare -a accounts
accounts=("${@:2}")
declare me
me="$(whoami)"
function cleanup () {
popd &>'/dev/null'
}
trap cleanup EXIT
function pprint () {
printf -- '%s ...\n' "${@}"
}
declare do_force
do_force='false'
for account_index in "${!accounts[@]}"; do
if [[ "${accounts[${account_index}]}" == '--force' ]] || [[ "${accounts[${account_index}]}" == '-f' ]]; then
do_force='true'
fi
if [[ "${accounts[${account_index}]}" == "${me}" ]]; then unset -v accounts["${account_index}"]; continue; fi
if ! id "${accounts[${account_index}]}" &>'/dev/null'; then unset -v accounts["${account_index}"]; continue; fi
done
if [[ "${#accounts[@]}" -eq '0' ]]; then
pprint 'Needs at least second account besides '"'${me}'"', exiting'
exit 0
fi
declare avail_keys
avail_keys="$(ssh-add -l)"
if ! grep -Piq "${ssh_key}" <<<"${avail_keys}"; then
pprint 'Key not loaded into agent, exiting'
exit 0
fi
function is_dirty () {
git update-index --refresh &>'/dev/null'
git diff-index --quiet HEAD -- || return 0
return 1
}
function we_are_ahead () {
[[ "$(git rev-list origin..HEAD)" ]] && return 0
return 1
}
function we_are_behind () {
[[ "$(git rev-list HEAD..origin)" ]] && return 0
return 1
}
pushd ~ &>'/dev/null'
if is_dirty; then pprint 'Dir '"'$(pwd)'"' is dirty, exiting'; git status; exit 0; fi
if we_are_behind; then pprint 'We are behind remote, exiting'; exit 0; fi
if we_are_ahead || [[ "${do_force}" == 'true' ]]; then
pprint 'Pushing from '"'${me}'"
git push
for account in "${accounts[@]}"; do
echo
pprint 'Pulling with '"'${account}'"
if [[ "${do_force}" == 'true' ]]; then
sudo --preserve-env=SSH_AUTH_SOCK su --shell /bin/bash --command 'cd; sudo --preserve-env=SSH_AUTH_SOCK git reset --hard' "${account}"
fi
sudo --preserve-env=SSH_AUTH_SOCK su --shell /bin/bash --command 'cd; sudo --preserve-env=SSH_AUTH_SOCK git pull; sudo find '"'"'.'"'"' \( -not -user '"${account}"' -or -not -group '"${account}"' \) -print0 | sudo xargs --no-run-if-empty --null -I '"'"'{}'"'"' chown --verbose --no-dereference '"${account}"':'"${account}"' '"'"'{}'"'"'' "${account}"
2023-03-16 23:48:55 +01:00
done
else
pprint 'Nothing to do'
fi