fixPermissions: simplify code, fix bugs

- avoid parsing permission strings
- fix memory leaks, a fix new/free mismatch and a compiler warning
- fix that only first updated-package was processed
- fix a potential stack overflow if packages.xml is huge
- minor refactoring for reducing duplicated code
- don't process packages without codePath
- fix path for deleting app data (currently unused anyway)
- fix file ownership on libs
- try not to mess up Android 5.0 app permissions

Patch set 4

- make fixing SELinux contexts an option with a check box
- add some notes / text to the themes

Patch set 6

- decouple "fix permissions" from "fix contexts"

Change-Id: Icc77ecc581befc5ce6e419b1f3b8ca189208c234
diff --git a/partition.cpp b/partition.cpp
index 409a688..80eb5aa 100644
--- a/partition.cpp
+++ b/partition.cpp
@@ -1654,9 +1654,6 @@
 	return Wipe_Encryption();
 #else
 	string dir;
-	#ifdef HAVE_SELINUX
-	fixPermissions perms;
-	#endif
 
 	// This handles wiping data on devices with "sdcard" in /data/media
 	if (!Mount(true))
@@ -2018,10 +2015,6 @@
 void TWPartition::Recreate_Media_Folder(void) {
 	string Command;
 
-	#ifdef HAVE_SELINUX
-	fixPermissions perms;
-	#endif
-
 	if (!Mount(true)) {
 		LOGERR("Unable to recreate /data/media folder.\n");
 	} else if (!TWFunc::Path_Exists("/data/media")) {
@@ -2029,7 +2022,13 @@
 		LOGINFO("Recreating /data/media folder.\n");
 		mkdir("/data/media", S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
 #ifdef HAVE_SELINUX
+		// Attempt to set the correct SELinux contexts on the folder
+		fixPermissions perms;
 		perms.fixDataInternalContexts();
+		// Afterwards, we will try to set the
+		// default metadata that we were hopefully able to get during
+		// early boot.
+		tw_set_default_metadata("/data/media");
 #endif
 		// Toggle mount to ensure that "internal sdcard" gets mounted
 		PartitionManager.UnMount_By_Path(Symlink_Mount_Point, true);