Add restore script, use it to move the latest lock file to the destinations

This commit is contained in:
Martin Larsson 2024-01-23 13:38:47 +01:00
parent 0a91afa541
commit 9cb44a8932
3 changed files with 60 additions and 7 deletions

39
restore.sh Executable file
View file

@ -0,0 +1,39 @@
#!/bin/zsh
source ./util_lib.sh
latest_lock=$(get_latest_lock)
has_lock=$(has_lock $latest_lock)
if [ $has_lock -eq 0 ]; then
echo "No lock exists, nothing to restore."
exit 0
fi
lock_dir="$LOCK_ROOT"/"$latest_lock"
# Iterate through the array of key-value pairs
for mapping in "${mappings[@]}"; do
current_mapping=("${(@s:|:)mapping}")
src="$lock_dir/$(basename "${current_mapping[1]}")"
dest="${current_mapping[2]}"
# If src exists at all? No matter if it's a file or directory
if [ ! -e "$src" ]; then
echo "$src does not exist, skipping."
continue
fi
# Remove destination if it is a directory
if [ -d "$src" ] && [ -d "$dest/${current_mapping[1]}" ]; then
echo "Removing $dest/${current_mapping[1]}"
rm -rf "$dest/${current_mapping[2]}"
fi
# Create destination directory
mkdir -p "$dest"
# Copy source to destination
cp -r "$src" "$dest"
done

View file

@ -2,9 +2,6 @@
source ./util_lib.sh source ./util_lib.sh
# Enable the NULL_GLOB option to handle cases where no subdirectories exist
setopt NULL_GLOB
# Create a lock dir for our current configs. # Create a lock dir for our current configs.
((latest_lock=$(get_latest_lock) + 1)) ((latest_lock=$(get_latest_lock) + 1))
lock_dir="$LOCK_ROOT"/"$latest_lock" lock_dir="$LOCK_ROOT"/"$latest_lock"
@ -21,10 +18,9 @@ for mapping in "${mappings[@]}"; do
# Check if destination directory exists # Check if destination directory exists
final="$dest/$src" final="$dest/$src"
if [ -e "$final" ]; then if [ -e "$final" ]; then
# If destination exists, move its contents to the .lock directory # mv "$final"/* "$lock_dest"
mkdir -p "$lock_dest" mv "$final" "$lock_dest"
mv "$final"/* "$lock_dest" echo "Moved \"$final\" to \"$lock_dest\""
echo "Moved existing contents of \"$final\" to \"$lock_dest\""
fi fi
# Create destination directory # Create destination directory

View file

@ -2,6 +2,9 @@
LOCK_ROOT=".lock" LOCK_ROOT=".lock"
# Enable the NULL_GLOB option to handle cases where no subdirectories exist
setopt NULL_GLOB
# Define a function to create key-value pairs # Define a function to create key-value pairs
create_mapping() { create_mapping() {
local input="$1" local input="$1"
@ -31,3 +34,18 @@ function get_latest_lock() {
echo $latest_lock echo $latest_lock
} }
function has_lock() {
local latest_lock=$1
# if first parameter does not exist, call get_latest_lock
if [[ -z $latest_lock ]]; then
latest_lock=$(get_latest_lock)
fi
if [[ $latest_lock -ne 0 ]]; then
echo 1
else
echo 0
fi
}