//
//  ViewController.m
//  FlashBack
//
//  Created by Micah Gomez on 3/27/19.
//  Copyright © 2019 Micah Gomez. All rights reserved.
//

#import "ViewController.h"
#include <spawn.h>
#include <signal.h>
#include "NSTask.h"
#import "InternalSetWallpaper.h"
#import "UIImage+Private.h"
#import <Photos/Photos.h>

@interface ViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@end

BOOL trial;
BOOL tweaksEnabled = YES;
NSString *stringTweaksEnabled = @"YES";
BOOL iconsEnabled = YES;
NSString *stringIconsEnabled = @"YES";
BOOL wallpaperEnabled = YES;
NSString *stringWallpaperEnabled = @"YES";

NSArray *_backupFolderArray;
NSString *_backupDirectory;
NSMutableString *sysCopyPrefsPath;
NSMutableString *sysCopySBPath;
NSMutableString *newBackupPrefsPath;
NSMutableString *newBackupSBPath;
NSMutableString *newBackupWPPath;
NSArray *_prefsFolderItemsRaw;
NSArray *_sbFolderItemsRaw;
NSArray *_filteredPrefsFolderItems;
NSArray *_filteredSBFolderItems;
NSMutableString *selectedBackupImageURL;
NSMutableString *selectedBackupURL;
NSString *backupNameSelected;

int selectedWallpaperStyle;

NSMutableString *lightHomeWPPath;
NSMutableString *darkHomeWPPath;
NSMutableString *lightLockWPPath;
NSMutableString *darkLockWPPath;

UIImage *lightHome;
UIImage *darkHome;
UIImage *lightLock;
UIImage *darkLock;



@implementation ViewController

//MARK: Handle bools for optional appliances

- (IBAction)tweaksSwitch:(id)sender {
    
    tweaksEnabled = [sender isOn];
    stringTweaksEnabled = tweaksEnabled == YES ? @"YES" : @"NO";
    NSLog(@"%@", stringTweaksEnabled);
    
}

- (IBAction)iconsSwitch:(id)sender {
    
    iconsEnabled = [sender isOn];
    stringIconsEnabled = iconsEnabled == YES ? @"YES" : @"NO";
    NSLog(@"%@", stringIconsEnabled);
    
}

- (IBAction)wallpaperSwitch:(id)sender {
    
    wallpaperEnabled = [sender isOn];
    stringWallpaperEnabled = wallpaperEnabled == YES ? @"YES" : @"NO";
    NSLog(@"%@", stringWallpaperEnabled);
    
}

//MARK: Create backup function

- (IBAction)createBackup:(id)sender {
    
    UIAlertController *createBackupAlert = [UIAlertController alertControllerWithTitle:@"Enter the Backup Name" message:@"Please do not use special symbols. Use only letters and numbers, no spaces." preferredStyle:UIAlertControllerStyleAlert];
    
    [createBackupAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"Backup Name";
        textField.secureTextEntry = NO;
    }];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Backup name is :%@", [[createBackupAlert textFields][0] text]);
        NSString *newBackupName=[[createBackupAlert textFields][0] text];
        
        if([[[createBackupAlert textFields][0] text] isEqual:@""]){
            NSLog(@"empty backup name!");
        }
        else{
            NSLog(@"Creating Backup");
            
            //MARK: Backup preferences
            if(tweaksEnabled == YES){
                _prefsFolderItemsRaw = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/var/mobile/Library/Preferences/" error:nil];
                
                NSLog(@"_prefsFolderItemsRaw:%@", _prefsFolderItemsRaw);
                
                NSPredicate *notApplePlistPredicate = [NSPredicate predicateWithFormat:@"NOT(SELF contains[c] 'apple')"];
                //NSPredicate *isPlistPredicate = [NSPredicate predicateWithFormat:@"SELF endswith[c] '.plist'"];
                NSPredicate *isPrefsPredicate = [NSPredicate predicateWithFormat:@"SELF LIKE[c] '*.*.*.plist'"];
                
                NSArray *_filteredPrefsFolderItems = [_prefsFolderItemsRaw filteredArrayUsingPredicate:notApplePlistPredicate];
                //_filteredPrefsFolderItems = [_filteredPrefsFolderItems filteredArrayUsingPredicate:isPlistPredicate];
                _filteredPrefsFolderItems = [_filteredPrefsFolderItems filteredArrayUsingPredicate:isPrefsPredicate];
                
                NSLog(@"_prefsFolderItems:%@", _filteredPrefsFolderItems);
                
                
                for (id file in _filteredPrefsFolderItems){
                    
                    sysCopyPrefsPath = [NSMutableString stringWithString: @"/private/var/mobile/Library/Preferences/"];
                    [sysCopyPrefsPath appendString: file];
                    
                    NSLog(@"File_Old_Location:%@", sysCopyPrefsPath);
                    
                    //newBackupPrefsPath = [NSMutableString stringWithString: @"/private/var/mobile/Documents/FlashBack/Backups/"];
                    newBackupPrefsPath = [NSMutableString stringWithString: @"/Library/FlashBack/Backups/"];
                    [newBackupPrefsPath appendString: newBackupName];
                    [newBackupPrefsPath appendString: @"/Preferences/"];
                    [[NSFileManager defaultManager] createDirectoryAtPath:newBackupPrefsPath withIntermediateDirectories:YES attributes:nil error:NULL];
                    [newBackupPrefsPath appendString: file];
                    
                    NSLog(@"File_New_Location:%@", newBackupPrefsPath);
                    
                    NSURL *sysCopyPrefsPathURL = [NSURL fileURLWithPath:sysCopyPrefsPath];
                    NSURL *newBackupPrefsPathURL = [NSURL fileURLWithPath:newBackupPrefsPath];
                    
                    
                    //if ( ([[NSFileManager defaultManager] isReadableFileAtPath:sysCopyPrefsPath]) && ([[NSFileManager defaultManager] isWritableFileAtPath:newBackupPrefsPath]) ){
                    
                    NSLog(@"Copying:%@", file);
                    if ([[NSFileManager defaultManager] copyItemAtURL:sysCopyPrefsPathURL toURL:newBackupPrefsPathURL error:nil]  == YES) {
                        NSLog (@"Copy successful - %@", file);
                    } else {
                        NSLog (@"Copy failed - %@", file);
                    }
                }
            }
            //MARK: End backup preferences
            //MARK: Backup Springboard
            if(iconsEnabled == YES){
                
                _sbFolderItemsRaw = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/var/mobile/Library/SpringBoard/" error:nil];
                
                NSLog(@"_sbFolderItemsRaw:%@", _sbFolderItemsRaw);
                
                NSPredicate *isIconPlistPredicate = [NSPredicate predicateWithFormat:@"(SELF contains[c] 'icon')"];
                //NSPredicate *isPlistPredicate = [NSPredicate predicateWithFormat:@"SELF endswith[c] '.plist'"];
                //NSPredicate *isPrefsPredicate = [NSPredicate predicateWithFormat:@"SELF LIKE[c] '*.*.*.plist'"];
                
                NSArray *_filteredSBFolderItems = [_sbFolderItemsRaw filteredArrayUsingPredicate:isIconPlistPredicate];
                //_filteredPrefsFolderItems = [_filteredPrefsFolderItems filteredArrayUsingPredicate:isPlistPredicate];
                //_filteredPrefsFolderItems = [_filteredPrefsFolderItems filteredArrayUsingPredicate:isPrefsPredicate];
                
                NSLog(@"_sbFolderItems:%@", _filteredSBFolderItems);
                
                
                for (id file in _filteredSBFolderItems){
                    
                    sysCopySBPath = [NSMutableString stringWithString: @"/private/var/mobile/Library/SpringBoard/"];
                    [sysCopySBPath appendString: file];
                    
                    NSLog(@"File_Old_Location:%@", sysCopySBPath);
                    
                    //newBackupPrefsPath = [NSMutableString stringWithString: @"/private/var/mobile/Documents/FlashBack/Backups/"];
                    newBackupSBPath = [NSMutableString stringWithString: @"/Library/FlashBack/Backups/"];
                    [newBackupSBPath appendString: newBackupName];
                    [newBackupSBPath appendString: @"/SpringBoard/"];
                    [[NSFileManager defaultManager] createDirectoryAtPath:newBackupSBPath withIntermediateDirectories:YES attributes:nil error:NULL];
                    [newBackupSBPath appendString: file];
                    
                    NSLog(@"File_New_Location:%@", newBackupSBPath);
                    
                    NSURL *sysCopySBPathURL = [NSURL fileURLWithPath:sysCopySBPath];
                    NSURL *newBackupSBPathURL = [NSURL fileURLWithPath:newBackupSBPath];
                    
                    
                    //if ( ([[NSFileManager defaultManager] isReadableFileAtPath:sysCopyPrefsPath]) && ([[NSFileManager defaultManager] isWritableFileAtPath:newBackupPrefsPath]) ){
                    
                    NSLog(@"Copying:%@", file);
                    if ([[NSFileManager defaultManager] copyItemAtURL:sysCopySBPathURL toURL:newBackupSBPathURL error:nil]  == YES) {
                        NSLog (@"Copy successful - %@", file);
                    } else {
                        NSLog (@"Copy failed - %@", file);
                    }
                }
            }
            //MARK: End backup Springboard
            
            /*
            UIImagePickerController* picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:NULL];
            */
            
            //MARK: Backup Wallpapers
            if(wallpaperEnabled == YES){
                
                newBackupWPPath = [NSMutableString stringWithString: @"/Library/FlashBack/Backups/"];
                [newBackupWPPath appendString: newBackupName];
                [newBackupWPPath appendString: @"/Wallpaper/"];
                [[NSFileManager defaultManager] createDirectoryAtPath:newBackupWPPath withIntermediateDirectories:YES attributes:nil error:NULL];
                
                lightHomeWPPath = [NSMutableString stringWithString: newBackupWPPath];
                [lightHomeWPPath appendString: @"lightHomeWP.png"];
                NSLog(@"%@", lightHomeWPPath);
                
                darkHomeWPPath = [NSMutableString stringWithString: newBackupWPPath];
                [darkHomeWPPath appendString: @"darkHomeWP.png"];
                NSLog(@"%@", darkHomeWPPath);
                
                lightLockWPPath = [NSMutableString stringWithString: newBackupWPPath];
                [lightLockWPPath appendString: @"lightLockWP.png"];
                NSLog(@"%@", lightLockWPPath);
                
                darkLockWPPath = [NSMutableString stringWithString: newBackupWPPath];
                [darkLockWPPath appendString: @"darkLockWP.png"];
                NSLog(@"%@", darkLockWPPath);
                
                [self selectWallpaperImageFunc];
            }
            //MARK: End backup wallpapers
            
            UIAlertController * finishedCreateAlert=   [UIAlertController
                                                        alertControllerWithTitle:@"Backup Creation Completed"
                                                        message:@"The backup has been successfully created"
                                                        preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"OK"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                
                _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
                [self->selectedBackupPickerView reloadAllComponents];
                
                [finishedCreateAlert dismissViewControllerAnimated:YES completion:nil];
                
            }];
            [finishedCreateAlert addAction:ok];
            
            [self presentViewController:finishedCreateAlert animated:YES completion:nil];
            
        }
        
        
    }];
    [createBackupAlert addAction:confirmAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Canelled");
    }];
    [createBackupAlert addAction:cancelAction];
    [self presentViewController:createBackupAlert animated:YES completion:nil];
}

//MARK: Wallpaper selection code

-(void)selectWallpaperImageFunc{
    UIAlertController *wallpaperSelectionAlert = [UIAlertController alertControllerWithTitle:@"Select Setup Wallpapers" message:@"Choose the wallpapers to apply for both Light and Dark mode on the Home and Lock Screen." preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* lightHomeAction = [UIAlertAction actionWithTitle:@"Light Mode Home Screen"
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
        selectedWallpaperStyle = 1;
        
        UIImagePickerController* picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        self.modalInPresentation = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction* darkHomeAction = [UIAlertAction actionWithTitle:@"Dark Mode Home Screen"
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
        selectedWallpaperStyle = 2;
        
        UIImagePickerController* picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        self.modalInPresentation = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction* lightLockAction = [UIAlertAction actionWithTitle:@"Light Mode Lock Screen"
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
        selectedWallpaperStyle = 3;
        
        UIImagePickerController* picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        self.modalInPresentation = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction* darkLockAction = [UIAlertAction actionWithTitle:@"Dark Mode Lock Screen"
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
        selectedWallpaperStyle = 4;
        
        UIImagePickerController* picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        self.modalInPresentation = YES;
        [self presentViewController:picker animated:NO completion:nil];
    }];
    UIAlertAction* doneAction = [UIAlertAction actionWithTitle:@"Done"
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
        
        if((lightHome == nil) || (darkHome == nil) || (lightLock == nil) || (darkLock == nil)){
            UIAlertController * finishedCreateAlert=   [UIAlertController
                                                        alertControllerWithTitle:@"Backup Creation Error"
                                                        message:@"The wallpapers were unable to be backed up. Please try again and make sure that all wallpapers are set before pressing done."
                                                        preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"OK"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
                [self->selectedBackupPickerView reloadAllComponents];
                [finishedCreateAlert dismissViewControllerAnimated:YES completion:nil];
                
            }];
            [finishedCreateAlert addAction:ok];
            
            [self presentViewController:finishedCreateAlert animated:YES completion:nil];
        }
        else{
        [UIImagePNGRepresentation(lightHome) writeToFile:lightHomeWPPath atomically:YES];
        [UIImagePNGRepresentation(darkHome) writeToFile:darkHomeWPPath atomically:YES];
        [UIImagePNGRepresentation(lightLock) writeToFile:lightLockWPPath atomically:YES];
        [UIImagePNGRepresentation(darkLock) writeToFile:darkLockWPPath atomically:YES];
        [wallpaperSelectionAlert dismissViewControllerAnimated:YES completion:nil];
        
        UIAlertController * finishedCreateAlert=   [UIAlertController
                                                    alertControllerWithTitle:@"Backup Creation Completed"
                                                    message:@"The backup has been successfully created"
                                                    preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            
            _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
            [self->selectedBackupPickerView reloadAllComponents];
            
            [finishedCreateAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        [finishedCreateAlert addAction:ok];
        
        [self presentViewController:finishedCreateAlert animated:YES completion:nil];
        }
    }];
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel"
                                                     style:UIAlertActionStyleCancel
                                                   handler:^(UIAlertAction * action) {
        UIAlertController * finishedCreateAlert=   [UIAlertController
                                                    alertControllerWithTitle:@"Backup Creation Completed"
                                                    message:@"The backup has been successfully created without any wallpapers"
                                                    preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            
            _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
            [self->selectedBackupPickerView reloadAllComponents];
            
            [finishedCreateAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        [finishedCreateAlert addAction:ok];
        
        [self presentViewController:finishedCreateAlert animated:YES completion:nil];
    }];
    [wallpaperSelectionAlert addAction:lightHomeAction];
    [wallpaperSelectionAlert addAction:lightLockAction];
    [wallpaperSelectionAlert addAction:darkHomeAction];
    [wallpaperSelectionAlert addAction:darkLockAction];
    [wallpaperSelectionAlert addAction:doneAction];
    [wallpaperSelectionAlert addAction:cancel];
    [self presentViewController:wallpaperSelectionAlert animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    switch (selectedWallpaperStyle) {
        case 1:
            lightHome = info[UIImagePickerControllerOriginalImage];
            break;
        case 2:
            darkHome = info[UIImagePickerControllerOriginalImage];
            break;
        case 3:
            lightLock = info[UIImagePickerControllerOriginalImage];
            break;
        case 4:
            darkLock = info[UIImagePickerControllerOriginalImage];
            break;
            
        default:
            break;
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self selectWallpaperImageFunc];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"picker cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self selectWallpaperImageFunc];
}

//MARK: Restore backup function

- (IBAction)restoreBackup:(id)sender {
    
    lightHome = [UIImage imageWithContentsOfFile:@"/Library/FlashBack/Backups/3/SBFolder/LockBackgroundThumbnail.jpg"];
    //darkHome = [UIImage imageWithContentsOfCPBitmapFile:@"/Library/FlashBack/Backups/3/SBFolder/LockBackgrounddark.cpbitmap" flags:kNilOptions];;
    
    //lock screen
    setLightAndDarkWallpaperImages(lightHome, lightHome, 1);
    //home screen
    setLightAndDarkWallpaperImages(lightHome, lightHome, 2);
    
    
    /*if (backupNameSelected == nil){
     
     UIAlertController * selectBackupAlert=   [UIAlertController
     alertControllerWithTitle:@"Select a Backup!"
     message:@"Scroll through the list then let it settle on an item to select the backup."
     preferredStyle:UIAlertControllerStyleAlert];
     
     UIAlertAction* ok = [UIAlertAction
     actionWithTitle:@"ok"
     style:UIAlertActionStyleDefault
     handler:^(UIAlertAction * action)
     {
     [selectBackupAlert dismissViewControllerAnimated:YES completion:nil];
     
     }];
     
     [selectBackupAlert addAction:ok];
     
     [self presentViewController:selectBackupAlert animated:YES completion:nil];
     
     }
     else{
     
     UIAlertController * restoreBackupAlert=   [UIAlertController
     alertControllerWithTitle:@"Restore Backup"
     message:@"Your device will revert to the selected backup! Please wait for your device to respring."
     preferredStyle:UIAlertControllerStyleAlert];
     
     UIAlertAction* ok = [UIAlertAction
     actionWithTitle:@"OK"
     style:UIAlertActionStyleDefault
     handler:^(UIAlertAction * action)
     {
     
     //RUN RESTORE SCRIPT
     
     NSTask *restoreTask = [[NSTask alloc] init];
     [restoreTask setLaunchPath:@"/bin/bash"];
     [restoreTask setArguments:@[ @"FBRestore", backupNameSelected]];
     [restoreTask launch];
     
     UIAlertController * finishedRestoreAlert=   [UIAlertController
     alertControllerWithTitle:@"Restoring from backup"
     message:@"Your device will respring when the process is completed."
     preferredStyle:UIAlertControllerStyleAlert];
     [self presentViewController:finishedRestoreAlert animated:YES completion:nil];
     
     [restoreBackupAlert dismissViewControllerAnimated:YES completion:nil];
     
     }];
     UIAlertAction* cancel = [UIAlertAction
     actionWithTitle:@"Cancel"
     style:UIAlertActionStyleDefault
     handler:^(UIAlertAction * action)
     {
     [restoreBackupAlert dismissViewControllerAnimated:YES completion:nil];
     
     }];
     
     [restoreBackupAlert addAction:cancel];
     [restoreBackupAlert addAction:ok];
     
     [self presentViewController:restoreBackupAlert animated:YES completion:nil];
     }*/
}

- (IBAction)updateBackup:(id)sender {
    
    if (backupNameSelected == nil){
        
        UIAlertController * updateBackupAlert=   [UIAlertController
                                                  alertControllerWithTitle:@"Select a Backup!"
                                                  message:@"Scroll through the list then let it settle on an item to select the backup."
                                                  preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"ok"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            [updateBackupAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        [updateBackupAlert addAction:ok];
        
        [self presentViewController:updateBackupAlert animated:YES completion:nil];
        
    }
    else{
        
        UIAlertController * updateBackupAlert=   [UIAlertController
                                                  alertControllerWithTitle:@"Update Backup"
                                                  message:@"The selected backup will be overwritten! Please wait until the completion pop-up appears"
                                                  preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            
            
            [updateBackupAlert dismissViewControllerAnimated:YES completion:nil];
            
            NSTask *deleteTask = [[NSTask alloc] init];
            [deleteTask setLaunchPath:@"/bin/bash"];
            [deleteTask setArguments:@[ @"FBDelete", backupNameSelected]];
            [deleteTask launch];
            [deleteTask waitUntilExit];
            
            NSTask *createTask = [[NSTask alloc] init];
            [createTask setLaunchPath:@"/bin/bash"];
            [createTask setArguments:@[ @"FBCreate", backupNameSelected]];
            [createTask launch];
            [createTask waitUntilExit];
            
            UIAlertController * finishedUpdateAlert=   [UIAlertController
                                                        alertControllerWithTitle:@"Backup Update Completed"
                                                        message:@"The backup has been successfully updated"
                                                        preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"OK"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                
                _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
                [self->selectedBackupPickerView reloadAllComponents];
                
                [finishedUpdateAlert dismissViewControllerAnimated:YES completion:nil];
                
            }];
            [finishedUpdateAlert addAction:ok];
            
            [self presentViewController:finishedUpdateAlert animated:YES completion:nil];
            
            
        }];
        UIAlertAction* cancel = [UIAlertAction
                                 actionWithTitle:@"Cancel"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
            [updateBackupAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        [updateBackupAlert addAction:cancel];
        [updateBackupAlert addAction:ok];
        
        [self presentViewController:updateBackupAlert animated:YES completion:nil];
    }
}

- (IBAction)packageBackup:(id)sender {
    
    if (trial == NO){
        
        if (backupNameSelected == nil){
            
            UIAlertController * selectBackupAlert=   [UIAlertController
                                                      alertControllerWithTitle:@"Select a Backup!"
                                                      message:@"Scroll through the list then let it settle on an item to select the backup."
                                                      preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"ok"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                [selectBackupAlert dismissViewControllerAnimated:YES completion:nil];
                
            }];
            
            [selectBackupAlert addAction:ok];
            
            [self presentViewController:selectBackupAlert animated:YES completion:nil];
            
        }
        else{
            
            UIAlertController * packageBackupAlert=   [UIAlertController
                                                       alertControllerWithTitle:@"Package Backup"
                                                       message:@"This will package the selected backup to a DEB file."
                                                       preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"OK"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                
                UIAlertController * packageBackupWait=   [UIAlertController
                                                          alertControllerWithTitle:@"Backup DEB"
                                                          message:@"The backup is being created. Please Wait. This dialogue will will be dismissed when finished. The  DEB can be found in [/User/Documents/FlashBackDEBs]"
                                                          preferredStyle:UIAlertControllerStyleAlert];
                
                [packageBackupAlert dismissViewControllerAnimated:YES completion:nil];
                
                [self presentViewController:packageBackupWait animated:YES completion:nil];
                
                
                NSTask *packageTask = [[NSTask alloc] init];
                [packageTask setLaunchPath:@"/bin/bash"];
                [packageTask setArguments:@[ @"FBPackage", backupNameSelected]];
                [packageTask launch];
                [packageTask waitUntilExit];
                
                
                [packageBackupWait dismissViewControllerAnimated:YES completion:nil];
                
            }];
            UIAlertAction* cancel = [UIAlertAction
                                     actionWithTitle:@"Cancel"
                                     style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction * action)
                                     {
                [packageBackupAlert dismissViewControllerAnimated:YES completion:nil];
                
            }];
            
            [packageBackupAlert addAction:cancel];
            [packageBackupAlert addAction:ok];
            
            [self presentViewController:packageBackupAlert animated:YES completion:nil];
        }
    }
    
    else{
        
        UIAlertController * noBackupDEBAlert =   [UIAlertController
                                                  alertControllerWithTitle:@"Creating DEBs is only available in the full version"
                                                  message:@"The free trial of FlashBack doesn't allow backing up setups to DEBs. Purchase the full version on PackIX for $1.50 for this!"
                                                  preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"ok"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            [noBackupDEBAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        [noBackupDEBAlert addAction:ok];
        
        [self presentViewController:noBackupDEBAlert animated:YES completion:nil];
        
    }
}

- (IBAction)helpMenu:(id)sender {
    
    UIAlertController * tutorialAlert=   [UIAlertController
                                          alertControllerWithTitle:@"Help"
                                          message:@"Create Backup (+): This will prompt you to enter a name for the backup which will be displayed in the box above.\n\nRestore (↺): This will revert your settings, wallpaper, and Icon Layout to the selected setup.\n\nUpdate (↑↓): This will overwrite the selected backup to cleanly update it.\n\nPackage (File Icon): This will generate a package in DEB format for you to share or back up for later, including installed tweaks.\n\nDelete (Trash Icon): This will delete the selected backup. These backups cannot be recovered!"
                                          preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"ok"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
        [tutorialAlert dismissViewControllerAnimated:YES completion:nil];
        
        
        UIAlertController * infoAlert=   [UIAlertController
                                          alertControllerWithTitle:@"Known issues"
                                          message:@"\nFor bug reports, please contact me via Twitter or the email available in the next pop-up dialogue.\n\nIf you have issues with the wallpaper, apply your wallpaper with AutoWall from https://jb365.github.io/ and update the backup.\n\nCredit for the DRM goes to @kushdabush on twitter"
                                          preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* okay = [UIAlertAction
                               actionWithTitle:@"ok"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action)
                               {
            [infoAlert dismissViewControllerAnimated:YES completion:nil];
            
            
            UIAlertController * contactAlert=   [UIAlertController
                                                 alertControllerWithTitle:@"Contact Me"
                                                 message:@"\nYou can contact my via Twitter or Email\n\n@micahpgomez\n\nmpg13@micahpgomez.dev\n\nhttps://www.micahpgomez.dev"
                                                 preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* okey = [UIAlertAction
                                   actionWithTitle:@"ok"
                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction * action)
                                   {
                [contactAlert dismissViewControllerAnimated:YES completion:nil];
                
            }];
            
            [contactAlert addAction:okey];
            
            [self presentViewController:contactAlert animated:YES completion:nil];
            
            
            
        }];
        
        [infoAlert addAction:okay];
        
        [self presentViewController:infoAlert animated:YES completion:nil];
        
        
        
    }];
    
    [tutorialAlert addAction:ok];
    
    [self presentViewController:tutorialAlert animated:YES completion:nil];
    
}

- (IBAction)deleteBackup:(id)sender {
    
    if (backupNameSelected == nil){
        
        UIAlertController * selectBackupAlert=   [UIAlertController
                                                  alertControllerWithTitle:@"Select a Backup!"
                                                  message:@"Scroll through the list then let it settle on an item to select the backup."
                                                  preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"ok"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            [selectBackupAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        [selectBackupAlert addAction:ok];
        
        [self presentViewController:selectBackupAlert animated:YES completion:nil];
        
    }
    
    UIAlertController * deleteBackupAlert=   [UIAlertController
                                              alertControllerWithTitle:@"Delete Backup"
                                              message:@"The selected backup will be deleted!"
                                              preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
        
        NSTask *deleteTask = [[NSTask alloc] init];
        [deleteTask setLaunchPath:@"/bin/bash"];
        [deleteTask setArguments:@[ @"FBDelete", backupNameSelected]];
        [deleteTask launch];
        [deleteTask waitUntilExit];
        
        UIAlertController * deleteFinishedAlert=   [UIAlertController
                                                    alertControllerWithTitle:@"Backup Deleted"
                                                    message:@"The backup has been deleted successfully"
                                                    preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* okey = [UIAlertAction
                               actionWithTitle:@"ok"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action)
                               {
            
            _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
            [self->selectedBackupPickerView reloadAllComponents];
            
            [deleteFinishedAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        [deleteFinishedAlert addAction:okey];
        
        [self presentViewController:deleteFinishedAlert animated:YES completion:nil];
        
        
        
        [deleteBackupAlert dismissViewControllerAnimated:YES completion:nil];
    }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
        
        [deleteBackupAlert dismissViewControllerAnimated:YES completion:nil];
        
    }];
    
    [deleteBackupAlert addAction:cancel];
    [deleteBackupAlert addAction:ok];
    
    [self presentViewController:deleteBackupAlert animated:YES completion:nil];
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    selectedBackupPickerView.delegate=self;
    selectedBackupPickerView.dataSource=self;
    
    // MARK: List of Backups is found and added to this array
    //_backupFolderArray = @[@"one",@"two",@"three"];
    _backupFolderArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Library/FlashBack/Backups/" error:nil];
    
    // MARK: DRM From @Kushdabush, commenting out for testing
    //pulled from https://github.com/DomienF/kushy-drm/blob/master/Tweak.xm
    
    UIAlertController * failedDRMAlert=   [UIAlertController
                                           alertControllerWithTitle:@"FlashBack appears to be pirated :("
                                           message:@"Please support small devs and purchase software. If you're unable to, please contact me, I'm happy to work things out! If you want to test it out, check out the trial version!"
                                           preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* failedDRMOk = [UIAlertAction
                                  actionWithTitle:@"ok"
                                  style:UIAlertActionStyleDefault
                                  handler:^(UIAlertAction * action)
                                  {
        [failedDRMAlert dismissViewControllerAnimated:YES completion:nil];
        //exit(0);
    }];
    
    UIAlertController * trialNoticeAlert=   [UIAlertController
                                             alertControllerWithTitle:@"Trial Notice"
                                             message:@"Thanks for checking out FlashBack! This trial allows you to give FlashBack a test run allowing for one backup. You can use that backup as a checkpoint to revert to after making changes."
                                             preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* trialOk = [UIAlertAction
                              actionWithTitle:@"ok"
                              style:UIAlertActionStyleDefault
                              handler:^(UIAlertAction * action)
                              {
        [trialNoticeAlert dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [failedDRMAlert addAction:failedDRMOk];
    [trialNoticeAlert addAction:trialOk];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"/var/lib/dpkg/info/com.mpg13.flashback.list"]){
        NSLog(@"FlashBack DRM Passed");
        trial = NO;
    }
    else{
        if ([[NSFileManager defaultManager] fileExistsAtPath:@"/var/lib/dpkg/info/com.mpg13.flashbackfree.list"]){
            NSLog(@"FlashBack Trial Mode");
            trial = YES;
            dispatch_async(dispatch_get_main_queue(), ^ {
                [self presentViewController:trialNoticeAlert animated:YES completion:nil];
            });
        }
        else{
            NSLog(@"DRM failed");
            dispatch_async(dispatch_get_main_queue(), ^ {
                [self presentViewController:failedDRMAlert animated:YES completion:nil];
            });
        }
    }
    
    trial = NO;
}


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (_backupFolderArray == nil){
        
        UIAlertController * emptyArrayAlert=   [UIAlertController
                                                alertControllerWithTitle:@"Let's start by making a backup!"
                                                message:@"Press 'Create Backup (+)' to get started!"
                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"ok"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
            [emptyArrayAlert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        [emptyArrayAlert addAction:ok];
        
        [self presentViewController:emptyArrayAlert animated:YES completion:nil];
        
    }
    else{
        backupNameSelected = [_backupFolderArray objectAtIndex:row];
        selectedBackupText.text=backupNameSelected;
        
        selectedBackupURL = [NSMutableString stringWithString: @"/Library/FlashBack/Backups/"];
        [selectedBackupURL appendString: backupNameSelected];
        
        selectedBackupImageURL=selectedBackupURL;
        
        [selectedBackupImageURL appendString: @"/Wallpaper/lightHomeWP.png"];
        NSLog(@"%@", selectedBackupImageURL);
        NSURL *url = [NSURL fileURLWithPath:selectedBackupImageURL];
        NSData *data = [NSData dataWithContentsOfURL:url];
        selectedBackupImage.image = [UIImage imageWithData:data];
        
        NSLog(@"%@", backupNameSelected);
    }
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    return _backupFolderArray.count;
    
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    return _backupFolderArray[row];
    
}
@end

