#!/bin/bash

# Author : epithetic

function MissingDir {
	echo "There doesn't appear to be a backup directory, cannot revert changes."
	exit
}

clear
echo "---------------------------------------"
echo "--- unipatch v0.8 by epithetic --------"
echo "---------------------------------------"
echo -e "\n\n"

dest="$1"
work="$(pwd -P)"

# Default destination to working directory
if [[ -z "$1" ]]; then
	dest="$(pwd -P)"
fi


if [[ ! -d "$dest/unip-backup" ]]; then MissingDir; fi

warncount=0
errcount=0

echo -e "\nPreparing to revert all unip patches...\n"

date="$(date '+%d/%m/%Y %H:%M:%S')"
echo "----------------------------------------" >> unipatch-log.txt
echo "$date | Reverting all changes to $dest" >> unipatch-log.txt
echo -e "----------------------------------------\n" >> unipatch-log.txt

echo "copying files..."

# Overwrite files with backups
cd "$dest"
cp -arfv "unip-backup/"* . >> unipatch-log.txt

# Read unip deletelog
if [[ -f "unip-backup/delete.log" ]]; then
	while IFS="" read -r p || [ -n "$p" ]
	do
		deletefile="$(echo "$p" | sed 's/\r$//' | sed "s/ //g" | sed "s/█/ /g" | sed "s/\\\/\//g")"
		if [[ -f "$dest/$deletefile" ]]; then
			echo "deleting $deletefile..."
			rm "$dest/$deletefile"
		else
			echo "Warning: $deletefile was slated for deletion, but missing."
			echo "WARNING: $dest/$deletefile was slated for deletion, but could not be found." >> unipatch-log.txt
			warncount=$((warncount + 1))
		fi
	done < "unip-backup/delete.log"

	# Remove deletelog now that we're done and delete backup folder
	rm "unip-backup/delete.log"
	if [[ -f "$dest/delete.log" ]]; then
		rm "$dest/delete.log"
	fi
fi

rm -rf "unip-backup"
rm "unipatch-installed.txt"

cd "$work"

echo -e "\nFinished reverting all unip patches with $warncount warnings and $errcount errors."

exit