/**
 * Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
 * Copyright (C) 2012-2023 Arm Limited (or its affiliates).
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */

#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <stdio.h>
#include "terminalprocess.h"
#include "terminal.h"

void TerminalProcess::modifyChildProcess()
{
    // child
    int subordinateFd = mTerminal->openSubordinate();
    if (setsid() < 0) {
        ::close(subordinateFd);
        _exit(-1);
    }
#ifdef TIOCSCTTY
    if (ioctl(subordinateFd, TIOCSCTTY, (char *) 0) < 0) {
        ::close(subordinateFd);
        _exit(-1);
    }
#endif
#if 0 // Use QProcess I/O
    if (dup2(subordinateFd, STDIN_FILENO) != STDIN_FILENO) {
        ::close(subordinateFd);
        _exit(-1);
    }
    if (dup2(subordinateFd, STDOUT_FILENO) != STDOUT_FILENO) {
        ::close(subordinateFd);
        _exit(-1);
    }
#endif

// ALL-3991: Having at least one pipe connected to the TTY is
// required to prevent sending an immediate SIGHUP on Linux,
// but leave it unconnected on MacOS to prevent a hang when the
// SSH process tries to write to stderr in the case of, for
// example, a disconnection.
#ifndef Q_OS_MACOS
    if (dup2(subordinateFd, STDERR_FILENO) != STDERR_FILENO) {
        ::close(subordinateFd);
        exit(-1);
    }
#endif
}

#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
void TerminalProcess::setupChildProcess()
{
    this->modifyChildProcess();
}
#endif
