Improvements to Update_Log_File

Change-Id: I5596759b0cb39e4448b6be382f9224feed70a5ea
diff --git a/twrp-functions.cpp b/twrp-functions.cpp
index 50df2ed..c39a6b2 100644
--- a/twrp-functions.cpp
+++ b/twrp-functions.cpp
@@ -261,6 +261,7 @@
 }
 
 void TWFunc::Copy_Log(string Source, string Destination) {
+	PartitionManager.Mount_By_Path(Destination, false);
 	FILE *destination_log = fopen(Destination.c_str(), "a");
 	if (destination_log == NULL) {
 		LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
@@ -282,11 +283,20 @@
 
 void TWFunc::Update_Log_File(void) {
 	// Copy logs to cache so the system can find out what happened.
-	Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
-	copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
-	chown("/cache/recovery/log", 1000, 1000);
-	chmod("/cache/recovery/log", 0600);
-	chmod("/cache/recovery/last_log", 0640);
+	if (PartitionManager.Mount_By_Path("/cache", false)) {
+		if (!TWFunc::Path_Exists("/cache/recovery/.")) {
+			LOGINFO("Recreating /cache/recovery folder.\n");
+			if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
+				LOGINFO("Unable to create /cache/recovery folder.\n");
+		}
+		Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
+		copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
+		chown("/cache/recovery/log", 1000, 1000);
+		chmod("/cache/recovery/log", 0600);
+		chmod("/cache/recovery/last_log", 0640);
+	} else {
+		LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
+	}
 
 	// Reset bootloader message
 	TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
@@ -304,11 +314,12 @@
 		}
 	}
 
-	if (!PartitionManager.Mount_By_Path("/cache", true) || (unlink("/cache/recovery/command") && errno != ENOENT)) {
-		LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
+	if (PartitionManager.Mount_By_Path("/cache", true)) {
+		if (unlink("/cache/recovery/command") && errno != ENOENT) {
+			LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
+		}
 	}
 
-	PartitionManager.UnMount_By_Path("/cache", true);
 	sync();
 }