Only grab terminal when necessery and restore when done (#414)

* Only grab terminal when necessery

* #414 bring to foreground also in noninteractive mode

Co-authored-by: Gabe Giosia <gabe@ghearing.com>
diff --git a/src/ios-deploy/ios-deploy.m b/src/ios-deploy/ios-deploy.m
index 06a0c81..3bb9b62 100644
--- a/src/ios-deploy/ios-deploy.m
+++ b/src/ios-deploy/ios-deploy.m
@@ -1083,7 +1083,8 @@
     _exit(WEXITSTATUS(status));
 }
 
-void bring_process_to_foreground() {
+pid_t bring_process_to_foreground() {
+    pid_t fgpid = tcgetpgrp(STDIN_FILENO);
     if (setpgid(0, 0) == -1)
         perror("setpgid failed");
 
@@ -1091,6 +1092,7 @@
     if (tcsetpgrp(STDIN_FILENO, getpid()) == -1)
         perror("tcsetpgrp failed");
     signal(SIGTTOU, SIG_DFL);
+    return fgpid;
 }
 
 void setup_dummy_pipe_on_stdin(int pfd[2]) {
@@ -1140,12 +1142,12 @@
         signal(SIGHUP, SIG_DFL);
         signal(SIGLLDB, SIG_DFL);
         child = getpid();
-
+        pid_t oldfgpid = 0;
         int pfd[2] = {-1, -1};
         if (isatty(STDIN_FILENO))
             // If we are running on a terminal, then we need to bring process to foreground for input
             // to work correctly on lldb's end.
-            bring_process_to_foreground();
+            oldfgpid = bring_process_to_foreground();
         else
             // If lldb is running in a non terminal environment, then it freaks out spamming "^D" and
             // "quit". It seems this is caused by read() on stdin returning EOF in lldb. To hack around
@@ -1169,6 +1171,10 @@
 
         // Notify parent we're exiting
         kill(parent, SIGLLDB);
+
+        if (oldfgpid) {
+            tcsetpgrp(STDIN_FILENO, oldfgpid);
+        }
         // Pass lldb exit code
         _exit(WEXITSTATUS(status));
     } else if (pid > 0) {