#!/usr/bin/env perl
use warnings;
use strict;
use File::Basename qw(basename);
use POSIX qw(tcgetpgrp tcsetpgrp WIFEXITED WEXITSTATUS WIFSIGNALED WIFSTOPPED WTERMSIG WUNTRACED WNOHANG);
use Time::HiRes qw(time);

# Signals to forward to the child process or group (if requested).
my @FORWARDED_SIGNALS = qw(HUP INT QUIT USR1 USR2 PIPE TERM);

# We replace SIGINT with SIGTERM when forwarding, because shells ignore SIGINT
# before launching child processes in background ("When job control is not in
# effect"): https://unix.stackexchange.com/a/652145
my $SIGINT_REPLACEMENT = "TERM";

# True if the tool is in a TTY foreground.
my $is_in_tty_foreground = 0;
my $is_first_stderr_print = 1;


#
# Tool entry point.
#
sub main {
  # Parse command line args.
  my @args = @ARGV;
  my $forward_signals_to = "";
  my $print_signals = 0;
  my $wait_timeout = 10;
  my $if_absent_path = "";
  my $if_absent_cleanup = "";
  while (@args) {
    if ($args[0] eq "--forward-signals-to-group") {
      shift(@args);
      $forward_signals_to = "group";
      next;
    } elsif ($args[0] eq "--forward-signals-to-child") {
      shift(@args);
      $forward_signals_to = "child";
      next;
    } elsif ($args[0] eq "--print-signals") {
      shift(@args);
      $print_signals = 1;
      next;
    } elsif ($args[0] =~ /^--wait-timeout(?:=(\d+))?/s) {
      shift(@args);
      $wait_timeout = int($1 || shift(@args));
      next;
    } elsif ($args[0] =~ /^--if-absent-path(?:=(.*))?/s) {
      shift(@args);
      $if_absent_path = $1 || shift(@args);
      next;
    } elsif ($args[0] =~ /^--if-absent-cleanup(?:=(.*))?/s) {
      shift(@args);
      $if_absent_cleanup = $1 || shift(@args);
      next;
    } else {
      last;
    }
  }

  if (!@args) {
    die(
      "run-in-separate-pgrp - launch a command in a newly created foreground process group\n" .
      "\n" .
      "usage:\n" .
      "  " . basename($0) . "\n" .
      "    [--forward-signals-to-group [--wait-timeout=N] | --forward-signals-to-child]\n" .
      "    [--print-signals]\n" .
      "    [--if-absent-path=PATH [--if-absent-cleanup=COMMAND]]\n" .
      "    command [arg ...]\n"
    );
  }

  $is_in_tty_foreground = -t *STDIN && tcgetpgrp(0) == getpgrp(0);
  if ($is_in_tty_foreground || $forward_signals_to eq "group" || $if_absent_path) {
    with_child(
      $forward_signals_to || "child",
      $wait_timeout,
      $print_signals,
      $if_absent_path,
      $if_absent_cleanup,
      \@args
    );
  } else {
    without_child(\@args);
  }
}

#
# Called when the launched program can just replace the current Perl process,
# and there is no need in tcsetpgrp() call since we're not in foreground or not
# in a TTY. This typically happens when the command is launched from some script
# or receives its STDIN from a pipe, and the user doesn't request signals
# forwarding to the subtree.
#
sub without_child {
  my ($args) = @_;
  setpgrp($$, $$) or die("setpgrp: $!\n");
  run_exec(@$args);
}

#
# Called when we need to launch the command in a child process and keep the
# parent waiting doing some stuff, like calling tcsetpgrp() or forwarding
# signals to the child/group.
#
sub with_child {
  my ($forward_signals_to, $wait_timeout, $print_signals, $if_absent_path, $if_absent_cleanup, $args) = @_;

  pipe(*READER, *WRITER) or die("pipe: $!\n");
  defined(our $pid = fork()) or die("fork: $!\n");

  if ($pid == 0) {
    # Child process: call setpgrp(), but we can't call tcsetpgrp() since it must
    # be done from the foreground process group (and after setpgrp() ends, the
    # current pid's process group is not foreground anymore).
    close(*READER);
    setpgrp($$, $$) or die("setpgrp: $!\n");

    # Message the parent that it can now call tcsetpgrp() to make this child's new
    # process group foreground.
    syswrite(*WRITER, "1");
    close(*WRITER);

    # Replace our own (child's) process with the command's process.
    run_exec(@$args);
  } else {
    # Parent process: wait for the child process to finish the setpgrp() call.
    close(*WRITER);
    sysread(*READER, my $buf, 1);
    close(*READER);

    # Assign the child's process group as foreground to the terminal, so that child
    # will be receiving ^C, ^Z etc.
    our $old_tcpgrp = 0;
    if ($is_in_tty_foreground) {
      $old_tcpgrp = tcgetpgrp(0);
      !defined($old_tcpgrp) || $old_tcpgrp == -1 and $old_tcpgrp = 0;
      # Tell OS that ^C, ^Z etc. should be received by $pid pgrp (i.e. set
      # $pid pgrp to control the terminal).
      tcsetpgrp(0, $pid) or die("tcsetpgrp $pid: $!\n");
      # If we got resumed (e.g. by "fg" in the shell), resume the child as well.
      $SIG{CONT} = sub { tcsetpgrp(0, $pid) and kill("CONT", -$pid) };
      # When the child and/or script exits, restore terminal controlling group
      # to the prev value. If we don't do it, all ^C signals will be lost, since
      # the terminal will try to deliver them to a dead child.
      END {
        if ($old_tcpgrp && tcgetpgrp(0) == $pid) {
          $SIG{TTOU} = 'IGNORE';
          tcsetpgrp(0, $old_tcpgrp) or die("tcsetpgrp $old_tcpgrp (restoring prev tcpgrp): $!\n");
        }
      }
    }

    # Forward signals received by this current script to the child.
    setup_forward_signals($pid, $forward_signals_to, $print_signals);

    # Loop until the child exits.
    my $code;
    my $need_if_absent_cleanup = 0;
    while (1) {
      if (!$need_if_absent_cleanup && $if_absent_path && !-e $if_absent_path) {
        print_stderr("$if_absent_path is now absent, killing ourselves");
        kill("INT", $$);
        $need_if_absent_cleanup = 1;
      }

      my $exited_pid = waitpid(-1, WUNTRACED | WNOHANG);
      if ($exited_pid == 0) {
        select(undef, undef, undef, 0.1);
        next;
      }

      $code = ${^CHILD_ERROR_NATIVE};
      if (WIFSTOPPED($code)) {
        # Child received ^Z: stop ourselves as if it were us who received ^Z.
        if ($old_tcpgrp && tcgetpgrp(0) == $pid) {
          kill("STOP", -$old_tcpgrp);
        }
        next;
      } else {
        # Child exited or doesn't exist anymore.
        last;
      }
    }

    # Wait for all processes in the group to exit. Works when both the user
    # pressed ^C (then it's the shell who delivers SIGINT to all processes in
    # the group), or when e.g. a SIGINT is sent to the script itself (then, it's
    # the setup_forward_signals() who forwards it to everyone in the group).
    if ($forward_signals_to eq "group") {
      my $start_time = time();
      while (kill(0, -$pid)) {
        select(undef, undef, undef, 0.1);
        if (time() - $start_time > $wait_timeout) {
          print_stderr("timed out waiting $wait_timeout second(s) for everyone in the process group -$pid to exit");
          last;
        }
      }
    }

    # Run cleanup command if needed.
    if ($need_if_absent_cleanup && $if_absent_cleanup) {
      system($if_absent_cleanup);
    }

    # It's important to properly propagate the exit code and signal to the
    # caller. I.e. if the wrapped command was killed with SIGTERM, the wrapper
    # will also show itself terminated with SIGTERM.
    if (WIFEXITED($code)) {
      exit(WEXITSTATUS($code));
    }
    if (WIFSIGNALED($code)) {
      for my $signal (@FORWARDED_SIGNALS) {
        $SIG{$signal} = undef;
      }
      kill(WTERMSIG($code), $$); # kill self with the same signal
    }
    exit($code >> 8);
  }
}

#
# Traps signals and forwards them to the $pid process or group.
#
sub setup_forward_signals {
  my ($pid, $forward_signals_to, $print_signals) = @_;
  for my $signal (@FORWARDED_SIGNALS) {
    $SIG{$signal} = sub {
      my $kill_signal = $signal eq "INT" ? $SIGINT_REPLACEMENT : $signal;
      my ($what, $pgrep_arg, $kill_id) = $forward_signals_to eq "group"
        ? ("processes in the group $pid", "-g $pid", -$pid)
        : ("child process $pid", undef, $pid);
      if ($print_signals) {
        my $ts = scalar(localtime);
        my $msg = "received SIG$signal at $ts, killing $what with SIG$kill_signal";
        # Note: ps tool doesn't support -g across platforms, so we use pgrep to
        # get the list of process ids and then ps to print nice command lines.
        my $pgrep_out = $pgrep_arg ? `pgrep $pgrep_arg` : "$pid";
        if ($pgrep_out) {
          $pgrep_out =~ s/\s+/ /sg;
          $pgrep_out =~ s/^\s+|\s+$//sg;
          my $ps_out = `ps -o pid,sess,pgid,command -p $pgrep_out`;
          if ($ps_out) {
            $ps_out =~ s/\s+$//sg;
            $msg .= ":\n$ps_out";
          }
        }
        $msg =~ s/[\r\n]+$//sg;
        print_stderr($msg);
      }
      kill($kill_signal, $kill_id);
    }
  }
}

#
# A shortcut to run exec() and handle errors.
#
sub run_exec {
  my (@args) = @_;
  exec(@args) or die("exec: $args[0]: $!\n");
}

#
# Prints a message to stderr with tool name prefix.
#
sub print_stderr {
  my ($msg) = @_;
  $msg = "run-in-separate-pgrp: $msg";
  if ($is_first_stderr_print && $is_in_tty_foreground) {
    $msg = "\n$msg";
  }
  print { \*STDERR } "$msg\n";
  $is_first_stderr_print = 0;
}

main();
