#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/param.h"

int
main()
{
  int pid1 = fork();
  if (pid1 < 0) {
    printf("[pid %d] Fork failed\n", getpid());
    exit(pid1);
  }

  if (pid1 == 0) {
    while (!pause(2))
      printf("[pid %d] Hello from target\n", getpid());
    exit(-1);
  }

  int pid = fork();
  if (pid < 0) {
    printf("[pid %d] Fork failed\n", getpid());
    exit(pid);
  }

  if (pid == 0) {
    pause(10);

    if (signal(pid1, SIGSTOP) == 0)
      printf("[pid %d] Target stopped\n", getpid());
    else {
      printf("[pid %d] Signal failed\n", getpid());
      exit(-1);
    }

    exit(0);
  }

  int ret = wait(0);
  if (ret == pid)
    printf("[pid %d] Part 1 done\n", getpid());
  else {
    printf("[pid %d] Wait failed\n", getpid());
    exit(ret);
  }

  pid = fork();
  if (pid < 0) {
    printf("[pid %d] Fork failed\n", getpid());
    exit(pid);
  }

  if (pid == 0) {
    pause(20);

    if (signal(pid1, SIGCONT) == 0)
      printf("[pid %d] Target started\n", getpid());
    else {
      printf("[pid %d] Signal failed\n", getpid());
      exit(-1);
    }

    exit(0);
  }

  ret = wait(0);
  if (ret == pid)
    printf("[pid %d] Part 2 done\n", getpid());
  else {
    printf("[pid %d] Wait failed\n", getpid());
    exit(ret);
  }

  pause(20);

  if (kill(pid1) == 0)
    printf("[pid %d] Child killed\n", getpid());
  else {
    printf("[pid %d] Kill failed\n", getpid());
    exit(-1);
  }

  pause(5);

  ret = wait(0);
  if (ret == pid1)
    printf("[pid %d] Kill succeeded\n", getpid());
  else {
    printf("[pid %d] Wait failed\n", getpid());
    exit(ret);
  }

  exit(0);
}
