#!/bin/sh

# ^C during an install or a removal on the command line lets the rpm run in
# progress finish, skips what is left and ends poldek with an error when
# something was skipped, as the shell does, rather than killing poldek.
# rpm and the scriptlet it runs ignore the ^C; a second one asks rpm to stop.
# A ^C before the first rpm run stops an install, upgrade-dist and removals
# with an error, and rpm does not run. Started with SIGINT ignored, poldek
# keeps ignoring it. On a terminal rpm reads from the pty it writes to, not
# from poldek's terminal, where sudo would take the ^C before poldek. A ^\,
# a hangup, a SIGTERM and a broken output wait for rpm to end, as a ^C does:
# poldek reads rpm's output to its end, asks rpm run without sudo to stop
# (not for a broken output), which rpm in a transaction puts off, starts no
# further set, in the shell either, and ends with the signal once the
# operation is over. A SIGTERM that comes while poldek starts rpm stops rpm too.
# The shell's history keeps each command typed, also when a signal ends it.

. ./sh/lib/setup
. ./sh/lib/repo-setup
. ./sh/lib/rpm-setup

ORIGREPO=
DESTINATION_REPO=
DEPENDENCY_SOLVER=3

setUp() {
    is_rpm_testing_off && return

    rpm_up
    # provide /bin/sh auto requirement
    rpm_build_installed sh -p /bin/sh

    RUNS="$TMPDIR/rpm-runs"
    rm -f $RUNS

    # stands for a ^C typed while rpm runs: it logs its run, sends SIGINT
    # to poldek and finishes
    FAKE_RPM="$TMPDIR/fake-rpm"
    printf '#!/bin/sh\necho rpm "$@" >> %s\nkill -INT $PPID\n' "$RUNS" > $FAKE_RPM
    chmod 755 $FAKE_RPM

    SIGINT_AT_INIT="$PWD/.libs/sigint_at_init.so"
    SIGNAL_AT_FORK="$PWD/.libs/signal_at_fork.so"
    TERMINAL_RPM="$TMPDIR/terminal-rpm"
}

# terminal_rpm N [quiet]: writes the fake rpm for N ^C typed on the terminal
# while rpm runs: SIGINT to every process of poldek's group. The fake rpm logs
# its run, a SIGTERM and its end; quiet, it first sends its output elsewhere,
# as a 'pm command' wrapper may.
terminal_rpm() {
    printf '#!/bin/sh\ntrap "echo TERM >> %s" TERM\n' "$RUNS"
    [ "${2:-}" = quiet ] && printf 'exec </dev/null >/dev/null 2>&1\n'
    printf 'echo rpm "$@" >> %s\n' "$RUNS"
    for i in $(seq $1); do
        printf 'kill -INT -- -$(cut -d" " -f5 /proc/$PPID/stat)\nsleep 1\n'
    done
    printf 'sleep 1\necho rpm done >> %s\n' "$RUNS"
}

# poldek_on_pipes|poldek_on_pty <args>: poldek with that fake rpm and SIGINT
# as on a terminal; rpm runs on pipes, or on a pty when poldek's output is one.
# The shell script(1) starts must not stay in poldek's group: the ^C would end it
poldek_on_pipes() {
    chmod 755 $TERMINAL_RPM
    setsid -w perl -e '$SIG{INT} = "DEFAULT"; exec @ARGV' \
        env LC_ALL=C $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $TERMINAL_RPM "$@" 2>&1
}

poldek_on_pty() {
    chmod 755 $TERMINAL_RPM
    timeout 30 script -qec "exec perl -e '\$SIG{INT} = \"DEFAULT\"; exec @ARGV' \
        env LC_ALL=C $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $TERMINAL_RPM $*" /dev/null </dev/null 2>&1
}

# signal_rpm SIG group|poldek [stops]: writes the fake rpm for SIG sent while
# rpm runs, to poldek's process group, as from the terminal, or to poldek
# alone. The fake rpm logs its run and a SIGTERM; a second later, as rpm in a
# transaction, it writes a line, logs whether the write went through, and
# logs its end. With stops, as rpm before its transaction, a SIGTERM ends it.
signal_rpm() {
    [ "${3:-}" = stops ] && onterm="; exit 1" || onterm=
    printf '#!/bin/sh\ntrap "echo TERM >> %s%s" TERM\n' "$RUNS" "$onterm"
    printf 'echo rpm "$@" >> %s\n' "$RUNS"
    if [ $2 = group ]; then
        printf 'kill -%s -- -$(cut -d" " -f5 /proc/$PPID/stat)\n' $1
    else
        printf 'kill -%s $PPID\n' $1
    fi
    printf 'sleep 1\necho late output\necho "late write $?" >> %s\n' "$RUNS"
    printf 'echo rpm done >> %s\n' "$RUNS"
}

# quit_on_pty|quit_on_pipes: poldek installing a with that fake rpm, SIGQUIT
# as on a terminal (a background job ignores it) and no core when it dies of
# it; on pipes in a group of its own, as on a terminal
quit_on_pty() {
    chmod 755 $TERMINAL_RPM
    timeout 30 script -qec "ulimit -c 0; exec perl -e '\$SIG{QUIT} = \"DEFAULT\"; exec @ARGV' \
        env LC_ALL=C $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $TERMINAL_RPM -u a" /dev/null </dev/null >/dev/null 2>&1
}

quit_on_pipes() {
    chmod 755 $TERMINAL_RPM
    (ulimit -c 0; timeout 30 setsid -w perl -e '$SIG{QUIT} = "DEFAULT"; exec @ARGV' \
        env LC_ALL=C $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $TERMINAL_RPM -u a) >/dev/null 2>&1
}

# rpm_done: whether the fake rpm got to its end within 5 s
rpm_done() {
    for i in $(seq 50); do
        grep -q 'rpm done' $RUNS 2>/dev/null && return 0
        sleep 0.1
    done
    return 1
}

# rpm_starts LOG: how many times poldek, run with -v, set out to run rpm; the
# fake rpm's own log misses a run that poldek stops before it gets anywhere
rpm_starts() {
    grep -ac 'Executing' "$1"
}

# assertRpmRanThrough <what>: the fake rpm of signal_rpm got to its end, its
# write after the signal went through, and poldek asked it to stop
assertRpmRanThrough() {
    assertTrue "$1: rpm did not get to its end: $(cat $RUNS)" rpm_done
    assertEquals "$1: rpm's output lost: $(cat $RUNS)" "1" \
                 "$(grep -c '^late write 0$' $RUNS)"
    assertEquals "$1: rpm not asked to stop: $(cat $RUNS)" "1" "$(grep -c TERM $RUNS)"
}

# with_sigint DEFAULT|IGNORE <command>: run it with SIGINT so set, whatever
# the tests themselves inherited (a background job ignores it)
with_sigint() {
    sig=$1; shift
    perl -e '$SIG{INT} = shift; exec @ARGV or die "$ARGV[0]: $!\n"' $sig "$@"
}

# the fake rpm needs no root, and sudo would not pass its SIGINT on to poldek
poldek_with_sigint() {
    sig=$1; shift
    with_sigint $sig $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $FAKE_RPM "$@"
}

# poldek_interrupted_before_rpm <args>: poldek gets SIGINT right after it
# sets up its ^C handler, as from a ^C typed before the operation gets to rpm
poldek_interrupted_before_rpm() {
    with_sigint DEFAULT env LC_ALL=C LD_PRELOAD=$SIGINT_AT_INIT \
                $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $FAKE_RPM "$@" 2>&1
}

# assertStoppedBeforeRpm <exit code> <output>
assertStoppedBeforeRpm() {
    assertEquals "exit code $1" "1" "$1"
    assertEquals "no SIGINT from $SIGINT_AT_INIT: $2" "1" \
                 "$(echo "$2" | grep -c '^sigint_at_init: SIGINT')"
    assertEquals "not reported: $2" "1" "$(echo "$2" | grep -c Interrupted)"
    assertEquals "rpm runs" "0" "$(cat $RUNS 2>/dev/null | wc -l)"
}

build() {
    build_package $REPO $@
}

testInterruptSkipsRemainingSets()
{
    skip_if_rpm_testing_off && return

    build a
    build b
    build c

    # three packages with no dependencies between them are three sets
    poldek_with_sigint DEFAULT -uv a b c
    rc=$?
    assertEquals "exit code $rc" "1" "$rc"
    assertEquals "rpm runs" "1" "$(wc -l < $RUNS)"
}

testInterruptLetsRemovalFinish()
{
    skip_if_rpm_testing_off && return

    rpm_build_installed a

    poldek_with_sigint DEFAULT uninstall a
    rc=$?
    assertEquals "exit code $rc" "0" "$rc"
    assertEquals "rpm runs" "1" "$(wc -l < $RUNS)"
}

testRpmReadsFromItsPty()
{
    skip_if_rpm_testing_off && return

    build a
    printf '#!/bin/sh\necho rpm stdin $(tty) stderr $(tty 0<&2) >> %s\n' "$RUNS" > $FAKE_RPM

    timeout 30 script -qec "$POLDEK_INSTALL -Ouse_sudo=n --pmcmd $FAKE_RPM -u a" \
        /dev/null </dev/null >/dev/null 2>&1
    assertEquals "rpm runs" "1" "$(grep -c '^rpm stdin /dev/' $RUNS)"
    set -- $(cat $RUNS)
    assertEquals "rpm stdin: $*" "$5" "$3"
}

testInterruptLetsRpmAndScriptletsRun()
{
    skip_if_rpm_testing_off && return

    build a
    terminal_rpm 1 > $TERMINAL_RPM

    out=$(poldek_on_pty -uv a)
    rc=$?
    assertEquals "exit code $rc: $out" "0" "$rc"
    assertEquals "rpm got the ^C: $out" "1" "$(grep -c 'rpm done' $RUNS)"
    assertEquals "rpm asked to stop" "0" "$(grep -c TERM $RUNS)"
    assertEquals "not told: $out" "1" \
                 "$(echo "$out" | grep -c 'Interrupted: rpm runs to the end')"
}

testSecondInterruptAsksRpmToStop()
{
    skip_if_rpm_testing_off && return

    build a
    terminal_rpm 2 > $TERMINAL_RPM

    out=$(poldek_on_pipes -uv a)
    assertEquals "rpm got the ^C: $out" "1" "$(grep -c 'rpm done' $RUNS)"
    assertEquals "rpm not asked to stop: $out" "1" "$(grep -c TERM $RUNS)"
    assertEquals "not told: $out" "1" \
                 "$(echo "$out" | grep -c '^notice: Stopping rpm: a transaction')"
}

testSecondInterruptAsksQuietRpmToStop()
{
    skip_if_rpm_testing_off && return

    build a
    terminal_rpm 2 quiet > $TERMINAL_RPM

    out=$(poldek_on_pipes -uv a)
    assertEquals "rpm not asked to stop: $out" "1" "$(grep -c TERM $RUNS)"
    assertEquals "not told: $out" "1" \
                 "$(echo "$out" | grep -c '^notice: Stopping rpm: a transaction')"
}

testQuitKeyLetsRpmRunOnPty()
{
    skip_if_rpm_testing_off && return

    build a
    signal_rpm QUIT group > $TERMINAL_RPM

    quit_on_pty
    assertEquals "rpm runs" "1" "$(grep -c '^rpm -' $RUNS)"
    assertRpmRanThrough "^\\"
}

testQuitKeyLetsRpmRunOnPipes()
{
    skip_if_rpm_testing_off && return

    build a
    signal_rpm QUIT group > $TERMINAL_RPM

    quit_on_pipes
    assertEquals "rpm runs" "1" "$(grep -c '^rpm -' $RUNS)"
    assertRpmRanThrough "^\\"
}

# a hangup of poldek's terminal, or a kill of poldek: rpm in a session of its
# own misses them; it is asked to stop, and the next set does not start
testHangupAndKillLetRpmRun()
{
    skip_if_rpm_testing_off && return

    build a
    build b

    for sig in HUP:129 TERM:143; do
        rm -f $RUNS
        signal_rpm ${sig%:*} poldek > $TERMINAL_RPM

        out=$(poldek_on_pipes -uv a b)
        rc=$?
        assertEquals "$sig: exit code $rc: $out" "${sig#*:}" "$rc"
        assertEquals "$sig: rpm runs" "1" "$(grep -c '^rpm -' $RUNS)"
        assertEquals "$sig: rpm started: $out" "1" "$(echo "$out" | rpm_starts -)"
        assertRpmRanThrough "$sig"
    done
}

# a SIGTERM that comes while poldek starts rpm, before it has rpm's pid, and
# rpm slow to get to its exec: rpm is asked to stop and does not run
testSignalWhileRpmStartsStopsIt()
{
    skip_if_rpm_testing_off && return

    build a
    signal_rpm TERM poldek > $TERMINAL_RPM
    chmod 755 $TERMINAL_RPM

    # the outer 2>/dev/null keeps the shell's own "Terminated" out of the
    # log; poldek's stderr still goes to $out through the inner 2>&1
    out=$(env LC_ALL=C LD_PRELOAD=$SIGNAL_AT_FORK $POLDEK_INSTALL -Ouse_sudo=n \
              --pmcmd $TERMINAL_RPM -uv a 2>&1) 2>/dev/null
    rc=$?
    assertEquals "exit code $rc: $out" "143" "$rc"
    assertEquals "no SIGTERM from $SIGNAL_AT_FORK: $out" "1" \
                 "$(echo "$out" | grep -c '^signal_at_fork: SIGTERM')"
    assertEquals "rpm ran: $(cat $RUNS 2>/dev/null)" "0" \
                 "$(cat $RUNS 2>/dev/null | grep -c '^rpm -')"
}

# poldek's shell on a terminal, a signal to it while the rpm of the first of
# two sets runs: rpm runs to its end, the second set does not start, and the
# shell ends after the command, with no prompt for the next one
testShellSignalStopsNextSet()
{
    skip_if_rpm_testing_off && return

    build a
    build b
    build c

    for sig_rc in HUP:129 TERM:143 QUIT:131; do
        sig=${sig_rc%:*}
        rm -f $RUNS $TMPDIR/poldek.log
        signal_rpm $sig poldek > $TERMINAL_RPM
        chmod 755 $TERMINAL_RPM

        printf 'install a b\ninstall c\n' | timeout 60 script -qec "ulimit -c 0; \
            env LC_ALL=C $POLDEK_INSTALL -v -Ouse_sudo=n --pmcmd $TERMINAL_RPM \
            --log $TMPDIR/poldek.log --shell" /dev/null >$TMPDIR/shell.out 2>&1
        rc=$?
        assertEquals "$sig: exit code" "${sig_rc#*:}" "$rc"
        assertEquals "$sig: the shell asked for a further command: $(cat $TMPDIR/shell.out)" \
                     "1" "$(grep -c 'poldek:/[^ ]*> ' $TMPDIR/shell.out)"
        assertEquals "$sig: rpm runs: $(cat $RUNS)" "1" "$(grep -c '^rpm -' $RUNS)"
        assertEquals "$sig: rpm started: $(cat $TMPDIR/poldek.log)" "1" \
                     "$(rpm_starts $TMPDIR/poldek.log)"
        assertRpmRanThrough "$sig"
    done
}

# a ^\ at the prompt of poldek's shell ends the shell, which runs no
# command typed after it
testShellQuitKeyAtPromptEndsShell()
{
    skip_if_rpm_testing_off && return

    build a
    rm -f $TMPDIR/poldek.log
    { for i in $(seq 100); do grep -qs 'package.* read' $TMPDIR/poldek.log && break; sleep 0.1; done
      sleep 1; printf '\034'; sleep 1; printf 'install a\n'; sleep 2; } |
        timeout 60 script -qec "ulimit -c 0; env LC_ALL=C $POLDEK_INSTALL -v \
            --pmcmd $FAKE_RPM --log $TMPDIR/poldek.log --shell" /dev/null >/dev/null 2>&1
    rc=$?
    assertEquals "exit code: $(cat $TMPDIR/poldek.log)" "131" "$rc"
    assertEquals "rpm runs: $(cat $RUNS 2>/dev/null)" "0" \
                 "$(cat $RUNS 2>/dev/null | grep -c '^rpm -')"
    assertEquals "a command ran: $(cat $TMPDIR/poldek.log)" "0" \
                 "$(grep -c 'Interrupted' $TMPDIR/poldek.log)"
}

# a hangup that ends poldek's shell during a command, as when its terminal
# closes, leaves the commands typed in the history file
testShellHistoryKeptAfterHangup()
{
    skip_if_rpm_testing_off && return

    build a
    rm -rf $TMPDIR/home
    mkdir $TMPDIR/home
    signal_rpm HUP poldek > $TERMINAL_RPM
    chmod 755 $TERMINAL_RPM

    printf 'ls a\ninstall a\n' | timeout 60 script -qec "env LC_ALL=C \
        HOME=$TMPDIR/home $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $TERMINAL_RPM \
        --shell" /dev/null >$TMPDIR/shell.out 2>&1
    rc=$?
    assertEquals "exit code: $(cat $TMPDIR/shell.out)" "129" "$rc"
    history=$(paste -sd, $TMPDIR/home/.poldek_history 2>/dev/null | sed 's/,/, /g')
    assertEquals "history: $history" "ls a, install a" "$history"
}

# rpm asked to stop before its transaction begins, as while it waits for the
# rpmdb lock, ends there
testHangupAndKillStopRpmBeforeItsTransaction()
{
    skip_if_rpm_testing_off && return

    build a

    for sig in HUP TERM; do
        rm -f $RUNS
        signal_rpm $sig poldek stops > $TERMINAL_RPM

        out=$(poldek_on_pipes -uv a)
        assertEquals "$sig: rpm not asked to stop: $out" "1" "$(grep -c TERM $RUNS)"
        assertEquals "$sig: rpm went on: $(cat $RUNS)" "0" "$(grep -c 'rpm done' $RUNS)"
    done
}

# poldek's output through a pipe whose reader ends while rpm runs, as tee
# does on a ^C: rpm is not asked to stop, and the next set does not start
testBrokenOutputLetsRpmRun()
{
    skip_if_rpm_testing_off && return

    build a
    build b
    cat > $TERMINAL_RPM <<EOF
#!/bin/sh
trap "echo TERM >> $RUNS" TERM
echo rpm "\$@" >> $RUNS
echo the reader ends here
sleep 1
echo late output
sleep 1
echo late output
echo "late write \$?" >> $RUNS
echo rpm done >> $RUNS
EOF

    rm -f $TMPDIR/poldek.log
    { poldek_on_pipes --log $TMPDIR/poldek.log -uv a b; echo $? > $TMPDIR/rc; } |
        sed '/the reader ends here/q' >/dev/null
    assertEquals "exit code $(cat $TMPDIR/rc)" "141" "$(cat $TMPDIR/rc)"
    assertEquals "rpm runs" "1" "$(grep -c '^rpm -' $RUNS)"
    assertEquals "rpm started: $(cat $TMPDIR/poldek.log)" "1" \
                 "$(rpm_starts $TMPDIR/poldek.log)"
    assertTrue "rpm did not get to its end: $(cat $RUNS)" rpm_done
    assertEquals "rpm's output lost: $(cat $RUNS)" "1" "$(grep -c '^late write 0$' $RUNS)"
    assertEquals "rpm asked to stop: $(cat $RUNS)" "0" "$(grep -c TERM $RUNS)"
    assertEquals "a second ^C asked for, though none came: $(cat $TMPDIR/poldek.log)" \
                 "0" "$(grep -c 'again stops it' $TMPDIR/poldek.log)"
}

# started with SIGHUP ignored, as under nohup, poldek keeps ignoring it
testIgnoredHangupStaysIgnored()
{
    skip_if_rpm_testing_off && return

    build a
    build b
    signal_rpm HUP poldek > $TERMINAL_RPM
    chmod 755 $TERMINAL_RPM

    perl -e '$SIG{HUP} = "IGNORE"; exec @ARGV' \
        env LC_ALL=C $POLDEK_INSTALL -Ouse_sudo=n --pmcmd $TERMINAL_RPM -uv a b >/dev/null 2>&1
    rc=$?
    assertEquals "exit code $rc" "0" "$rc"
    assertEquals "rpm runs" "2" "$(grep -c '^rpm -' $RUNS)"
    assertEquals "rpm asked to stop: $(cat $RUNS)" "0" "$(grep -c TERM $RUNS)"
}

# a ^C is kept from rpm without ignoring SIGINT, which the scriptlets and the
# daemons they start would inherit; the fake rpm runs a scriptlet that sends
# itself a SIGINT
testScriptletsStopOnInterrupt()
{
    skip_if_rpm_testing_off && return

    build a
    cat > $TERMINAL_RPM <<EOF
#!/bin/sh
echo rpm "\$@" >> $RUNS
sh -c 'kill -INT \$\$; echo SIGINT ignored >> $RUNS'
EOF

    poldek_on_pipes -u a
    assertEquals "rpm runs" "1" "$(grep -c '^rpm ' $RUNS)"
    assertEquals "the scriptlet ignored SIGINT" "0" "$(grep -c 'SIGINT ignored' $RUNS)"
}

testInterruptBeforeRpmStopsInstall()
{
    skip_if_rpm_testing_off && return

    build a

    out=$(poldek_interrupted_before_rpm -u a)
    assertStoppedBeforeRpm "$?" "$out"
}

testInterruptBeforeRpmStopsUpgradeDist()
{
    skip_if_rpm_testing_off && return

    rpm_build_installed a 1-1
    build a 2-1

    poldek_with_sigint DEFAULT --upgrade-dist
    assertEquals "a not upgraded without ^C" "1" "$(grep -c 'a-2-1' $RUNS)"
    rm -f $RUNS

    out=$(poldek_interrupted_before_rpm --upgrade-dist)
    assertStoppedBeforeRpm "$?" "$out"
}

testInterruptBeforeRpmStopsRemoval()
{
    skip_if_rpm_testing_off && return

    rpm_build_installed a
    rpm_build_installed b -r a

    # b requires a, so removing a takes b too
    poldek_with_sigint DEFAULT -e a
    assertEquals "b not removed with a without ^C" "1" "$(grep -c 'b-1-1' $RUNS)"
    rm -f $RUNS

    out=$(poldek_interrupted_before_rpm -e a)
    assertStoppedBeforeRpm "$?" "$out"
}

testIgnoredInterruptStaysIgnored()
{
    skip_if_rpm_testing_off && return

    build a
    build b
    build c

    poldek_with_sigint IGNORE -uv a b c
    rc=$?
    assertEquals "exit code $rc" "0" "$rc"
    assertEquals "rpm runs" "3" "$(wc -l < $RUNS)"
}

. ./sh/lib/shunit2
