diff --git a/restore.sh b/restore.sh new file mode 100755 index 0000000..581b385 --- /dev/null +++ b/restore.sh @@ -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 diff --git a/upgrade.sh b/upgrade.sh index 3c1fc6f..a03abe3 100755 --- a/upgrade.sh +++ b/upgrade.sh @@ -2,9 +2,6 @@ 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. ((latest_lock=$(get_latest_lock) + 1)) lock_dir="$LOCK_ROOT"/"$latest_lock" @@ -21,10 +18,9 @@ for mapping in "${mappings[@]}"; do # Check if destination directory exists final="$dest/$src" if [ -e "$final" ]; then - # If destination exists, move its contents to the .lock directory - mkdir -p "$lock_dest" - mv "$final"/* "$lock_dest" - echo "Moved existing contents of \"$final\" to \"$lock_dest\"" + # mv "$final"/* "$lock_dest" + mv "$final" "$lock_dest" + echo "Moved \"$final\" to \"$lock_dest\"" fi # Create destination directory diff --git a/util_lib.sh b/util_lib.sh index c7f069c..94b61b0 100644 --- a/util_lib.sh +++ b/util_lib.sh @@ -2,6 +2,9 @@ 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 create_mapping() { local input="$1" @@ -31,3 +34,18 @@ function get_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 +}