#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
#include <stdlib.h>

#include "FullChainTest.h"
#include "../../Exploit/Probe/ServiceProbe.h"

@class ExploitViewController;

static ExploitViewController *gVC = nil;

// C callbacks invoked from the exploit worker thread. Prototypes must match
// the function-pointer types declared in FullChainTest.h exactly.
static void exploit_log_cb(const char *message);
static void exploit_progress_cb(int stage, int total, const char *message);
static void core_log_cb(log_level_t level, const char *message);

#pragma mark - View Controller

@interface ExploitViewController : UIViewController

@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UIButton *probeButton;
@property (nonatomic, strong) UITextView *logTextView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UILabel *stageLabel;
@property (nonatomic, strong) UILabel *statusLabel;

- (void)appendLog:(NSString *)message;

@end

@implementation ExploitViewController {
    full_chain_ctx_t *_ctx;
    dispatch_queue_t _exploitQueue;
    BOOL _isRunning;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"iOS 18.7.8 Exploit Chain";
    self.view.backgroundColor = [UIColor systemBackgroundColor];
    gVC = self;

    CGFloat w = self.view.bounds.size.width;

    self.stageLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 100, w - 32, 22)];
    self.stageLabel.text = @"Stage: -";
    self.stageLabel.font = [UIFont monospacedSystemFontOfSize:12 weight:UIFontWeightRegular];
    self.stageLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.stageLabel];

    self.statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 126, w - 32, 22)];
    self.statusLabel.text = @"Status: Idle";
    self.statusLabel.font = [UIFont monospacedSystemFontOfSize:12 weight:UIFontWeightRegular];
    self.statusLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.statusLabel];

    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(16, 154, w - 32, 4)];
    self.progressView.progress = 0.0f;
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.progressView];

    self.startButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.startButton.frame = CGRectMake(16, 172, w - 32, 40);
    [self.startButton setTitle:@"Start Exploit" forState:UIControlStateNormal];
    self.startButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.startButton addTarget:self action:@selector(startExploit:) forControlEvents:UIControlEventTouchUpInside];
    self.startButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.startButton];

    self.probeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.probeButton.frame = CGRectMake(16, 214, w - 32, 40);
    [self.probeButton setTitle:@"Probe Services (safe)" forState:UIControlStateNormal];
    self.probeButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.probeButton addTarget:self action:@selector(probeServices:) forControlEvents:UIControlEventTouchUpInside];
    self.probeButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.probeButton];

    CGFloat logY = 264;
    CGFloat logH = self.view.bounds.size.height - logY - 16;
    self.logTextView = [[UITextView alloc] initWithFrame:CGRectMake(16, logY, w - 32, logH)];
    self.logTextView.editable = NO;
    self.logTextView.font = [UIFont monospacedSystemFontOfSize:10 weight:UIFontWeightRegular];
    self.logTextView.text = @"Ready. Tap \"Start Exploit\".\n";
    self.logTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.logTextView];

    _exploitQueue = dispatch_queue_create("com.keepantidev.exploit.chain", DISPATCH_QUEUE_SERIAL);
}

- (void)startExploit:(id)sender {
    if (_isRunning) return;

    if (!_ctx) {
        _ctx = calloc(1, sizeof(full_chain_ctx_t));
    }

    _isRunning = YES;
    self.startButton.enabled = NO;
    [self.startButton setTitle:@"Running..." forState:UIControlStateDisabled];
    self.logTextView.text = @"";
    self.progressView.progress = 0.0f;
    self.statusLabel.text = @"Status: Running";

    dispatch_async(_exploitQueue, ^{
        exploit_error_t initErr = full_chain_init(self->_ctx);
        if (initErr != EXPLOIT_SUCCESS) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self appendLog:[NSString stringWithFormat:@"Init failed: %s", exploit_error_string(initErr)]];
                [self setRunning:NO];
            });
            return;
        }

        self->_ctx->log_callback = exploit_log_cb;
        self->_ctx->progress_callback = exploit_progress_cb;

        exploit_error_t err = full_chain_run(self->_ctx);

        dispatch_async(dispatch_get_main_queue(), ^{
            if (err == EXPLOIT_SUCCESS) {
                [self appendLog:@"\n=== EXPLOIT CHAIN SUCCESSFUL ==="];
                self.statusLabel.text = @"Status: SUCCESS!";
            } else {
                [self appendLog:[NSString stringWithFormat:@"\n=== EXPLOIT FAILED: %s ===", exploit_error_string(err)]];
                self.statusLabel.text = @"Status: FAILED";
            }
            [self setRunning:NO];
        });
    });
}

- (void)setRunning:(BOOL)running {
    _isRunning = running;
    self.startButton.enabled = !running;
    [self.startButton setTitle:(running ? @"Running..." : @"Start Exploit") forState:UIControlStateNormal];
}

- (void)probeServices:(id)sender {
    self.logTextView.text = @"";
    self.statusLabel.text = @"Status: Probing IOKit services...";

    exploit_set_log_callback(core_log_cb);

    dispatch_async(_exploitQueue, ^{
        service_probe_run();
        dispatch_async(dispatch_get_main_queue(), ^{
            self.statusLabel.text = @"Status: Probe done";
        });
    });
}

- (void)appendLog:(NSString *)message {
    self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"%@\n", message];
    NSRange range = NSMakeRange(self.logTextView.text.length, 0);
    [self.logTextView scrollRangeToVisible:range];
}

@end

#pragma mark - C callbacks

static void exploit_log_cb(const char *message) {
    NSString *msg = [NSString stringWithUTF8String:(message ? message : "(null)")];
    dispatch_async(dispatch_get_main_queue(), ^{
        [gVC appendLog:msg];
    });
}

static void exploit_progress_cb(int stage, int total, const char *message) {
    NSString *msg = [NSString stringWithUTF8String:(message ? message : "")];
    dispatch_async(dispatch_get_main_queue(), ^{
        gVC.stageLabel.text = [NSString stringWithFormat:@"Stage: %d/%d - %s",
                               stage, total, exploit_stage_name(stage)];
        gVC.progressView.progress = (total > 0) ? ((float)stage / (float)total) : 0.0f;
        gVC.statusLabel.text = msg;
    });
}

static void core_log_cb(log_level_t level, const char *message) {
    (void)level;
    NSString *msg = [NSString stringWithUTF8String:(message ? message : "")];
    dispatch_async(dispatch_get_main_queue(), ^{
        [gVC appendLog:msg];
    });
}

#pragma mark - App Delegate

@interface ExploitAppDelegate : UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@end

@implementation ExploitAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    ExploitViewController *vc = [[ExploitViewController alloc] initWithNibName:nil bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];

    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([ExploitAppDelegate class]));
    }
}
