#!/bin/sh

# The hooks in <hooks dir>/pre-install.d run once before the first rpm run
# of an operation and the ones in post-install.d once after the last one,
# however many package sets the operation installs. A failing pre-install
# hook stops the operation; a failing post-install one is only reported.
# An operation interrupted while its pre-install hooks run starts neither
# another pre-install hook nor rpm, and its post-install hooks still run.
# A hangup, a SIGTERM, a ^\ or a broken output while rpm runs lets rpm and
# the post-install hooks run before poldek ends with the signal; a program
# using libpoldek that handles the signal itself gets it then, and its next
# operation runs as usual. In poldek's shell a second SIGTERM after one from
# a pre-install hook ends poldek at once.
# Hook output keeps its lines on the terminal and in the log file, where
# each line follows the hook's name.
# Hooks do not run for rpm test runs, nor with a root other than /.

. ./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

    HOOKS="$TMPDIR/hooks"
    HOOKS_LOG="$TMPDIR/hooks.log"
    rm -rf $HOOKS $HOOKS_LOG
    mkdir -p $HOOKS/pre-install.d $HOOKS/post-install.d
    hook pre-install.d log pre
    hook post-install.d log post

    # logs its runs instead of installing, so poldek may work on /
    FAKE_RPM="$TMPDIR/fake-rpm"
    printf '#!/bin/sh\necho rpm >> %s\n' "$HOOKS_LOG" > $FAKE_RPM
    chmod 755 $FAKE_RPM

    POLDEK_ON_ROOT="$RAW_POLDEK --pmcmd $FAKE_RPM --st dir -s $REPO --root /"
    POLDEK_HOOKS="$POLDEK_ON_ROOT -Ohooks_dir=$HOOKS"
    SIGNAL_AT_RESTORE="$PWD/.libs/signal_at_restore.so"
    LIBRARY_USER="$PWD/.libs/library_user.so"
}

# hook <subdir> <name> <word to log> [exit code]
hook() {
    printf '#!/bin/sh\necho %s >> %s\nexit %s\n' "$3" "$HOOKS_LOG" "${4:-0}" > $HOOKS/$1/$2
    chmod 755 $HOOKS/$1/$2
}

build() {
    build_package $REPO $@
}

# what ran, in order, on one line
runs() {
    [ -f $HOOKS_LOG ] && tr '\n' ' ' < $HOOKS_LOG | sed 's/ $//'
}

# assertRuns <what should have run, in order>
assertRuns() {
    assertEquals "ran: '$(runs)'" "$1" "$(runs)"
}

testHooksRunOncePerOperation()
{
    skip_if_rpm_testing_off && return

    build hooka
    build hookb
    build hookc

    # three packages with no dependencies between them are three sets
    $POLDEK_HOOKS -uv hooka hookb hookc
    assertEquals "install failed" "0" "$?"
    assertRuns "pre rpm rpm rpm post"
}

testFailingPreHookStopsOperation()
{
    skip_if_rpm_testing_off && return

    build hooka
    build hookb
    hook pre-install.d log pre 1

    $POLDEK_HOOKS -uv hooka hookb
    rc=$?
    assertTrue "install expected to fail" "[ $rc -ne 0 ]"
    assertRuns "pre"
}

testFailingPostHookIsOnlyReported()
{
    skip_if_rpm_testing_off && return

    build hooka
    hook post-install.d log post 1

    out=$(LC_ALL=C $POLDEK_HOOKS -uv hooka 2>&1)
    assertEquals "install failed" "0" "$?"
    assertRuns "pre rpm post"
    echo "$out" | grep -q "post-install.d/log exited with 1"
    assertEquals "failing post-install hook not reported: $out" "0" "$?"
}

testHooksRunInNameOrderSkippingBackupsAndDotFiles()
{
    skip_if_rpm_testing_off && return

    build hooka
    rm -f $HOOKS/pre-install.d/log
    hook pre-install.d 20-b b
    hook pre-install.d 10-a a
    hook pre-install.d 30-c.sh c
    hook pre-install.d x.rpmnew rpmnew
    hook pre-install.d x~ backup
    hook pre-install.d .hidden hidden
    hook pre-install.d README readme
    chmod 644 $HOOKS/pre-install.d/README

    $POLDEK_HOOKS -uv hooka
    assertEquals "install failed" "0" "$?"
    assertRuns "a b c rpm post"
}

# poldek interrupted while a pre-install hook runs starts neither the next
# hook nor rpm, as it starts no other step; the post-install hooks still run
testInterruptDuringPreHookStartsNoFurtherStep()
{
    skip_if_rpm_testing_off && return

    build hooka
    printf '#!/bin/sh\necho pre >> %s\nkill -INT $PPID\n' "$HOOKS_LOG" \
        > $HOOKS/pre-install.d/log
    hook pre-install.d log2 pre2

    out=$(perl -e '$SIG{INT} = "DEFAULT"; exec @ARGV' $POLDEK_HOOKS -Ouse_sudo=n -uv hooka 2>&1)
    rc=$?
    assertEquals "exit code $rc: $out" "1" "$rc"
    assertRuns "pre post"
}

# a SIGTERM to poldek while rpm runs lets rpm end and the post-install hooks
# run, as a ^C does, and then ends poldek
testPostHooksRunAfterSignal()
{
    skip_if_rpm_testing_off && return

    build hooka
    printf '#!/bin/sh\necho rpm >> %s\nkill -TERM $PPID\nsleep 1\n' "$HOOKS_LOG" > $FAKE_RPM

    $POLDEK_HOOKS -Ouse_sudo=n -uv hooka >/dev/null 2>&1
    rc=$?
    assertEquals "exit code $rc" "143" "$rc"
    assertRuns "pre rpm post"
}

# a reader of poldek's output gone while rpm runs, as tee on a ^C: rpm runs
# to its end and the post-install hooks run before poldek ends with SIGPIPE
testPostHooksRunAfterBrokenOutput()
{
    skip_if_rpm_testing_off && return

    build hooka
    printf '#!/bin/sh\necho rpm >> %s\necho the reader ends here\nsleep 1\necho late output\n' \
        "$HOOKS_LOG" > $FAKE_RPM

    { $POLDEK_HOOKS -uv hooka 2>&1; echo $? > $TMPDIR/rc; } |
        sed '/the reader ends here/q' >/dev/null
    assertEquals "exit code $(cat $TMPDIR/rc)" "141" "$(cat $TMPDIR/rc)"
    assertRuns "pre rpm post"
}

# a SIGTERM that comes just as poldek stops holding it after rpm is taken
# either as one while rpm ran or as one after; noted, it stays caught, and a
# second one does not end poldek in the middle of a post-install hook, whose
# write to poldek would then fail
testSignalAsRpmEndsCutsNoPostHookShort()
{
    skip_if_rpm_testing_off && return

    build hooka
    printf '#!/bin/sh\nset -e\necho post-start >> %s\nkill -TERM $PPID\nsleep 1\necho hook output\necho post-end >> %s\n' \
        "$HOOKS_LOG" "$HOOKS_LOG" > $HOOKS/post-install.d/log

    # 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 LD_PRELOAD=$SIGNAL_AT_RESTORE $POLDEK_HOOKS -Ouse_sudo=n -uv hooka 2>&1) 2>/dev/null
    rc=$?
    assertEquals "no SIGTERM from $SIGNAL_AT_RESTORE: $out" "1" \
                 "$(echo "$out" | grep -c '^signal_at_restore: SIGTERM')"
    assertEquals "exit code $rc" "143" "$rc"
    case "$(runs)" in
        "pre rpm"|"pre rpm post-start post-end") ;;
        *) fail "a post-install hook cut short: '$(runs)'" ;;
    esac
}

# a program that uses libpoldek and handles a hangup itself gets the one that
# came while rpm ran once the post-install hooks have run, and its next
# operation runs rpm, which nothing asks to stop: here poldek's shell, which
# keeps one context and one sigint_init() for all its commands, as such a
# program does, and leaves a hangup to it
testCallerGetsSignalAfterPostHooks()
{
    skip_if_rpm_testing_off && return

    build hooka
    build hookb
    # the first rpm run gets poldek a hangup; a SIGTERM to rpm is logged
    cat > $FAKE_RPM <<EOF
#!/bin/sh
trap "echo rpm-stopped >> $HOOKS_LOG" TERM
echo rpm >> $HOOKS_LOG
[ -f $TMPDIR/hup-sent ] && exit 0
: > $TMPDIR/hup-sent
kill -HUP \$PPID
sleep 1
EOF
    rm -f $TMPDIR/hup-sent

    printf 'install hooka\ninstall hookb\n' | timeout 60 script -qec \
        "env LD_PRELOAD=$LIBRARY_USER CALLER_LOG=$HOOKS_LOG $POLDEK_HOOKS -Ouse_sudo=n --shell" \
        /dev/null >/dev/null 2>&1
    rc=$?
    assertEquals "exit code" "0" "$rc"
    assertRuns "pre rpm rpm-stopped post caller pre rpm post"
}

# the same for a program that never calls sigint_init(): the hangup reaches
# its handler after the post-install hooks, not as rpm ends
testCallerWithoutSigintInitGetsSignalAfterPostHooks()
{
    skip_if_rpm_testing_off && return

    build hooka
    printf '#!/bin/sh\necho rpm >> %s\nkill -HUP $PPID\nsleep 1\n' "$HOOKS_LOG" > $FAKE_RPM

    env LD_PRELOAD=$LIBRARY_USER CALLER_LOG=$HOOKS_LOG CALLER_NO_SIGINT_INIT=1 \
        $POLDEK_HOOKS -Ouse_sudo=n -uv hooka >/dev/null 2>&1
    rc=$?
    assertEquals "exit code $rc" "1" "$rc"
    assertRuns "pre rpm post caller"
}

# a SIGTERM or a ^\ to poldek's shell while a pre-install hook runs keeps
# rpm from starting, and the shell ends after the command
testShellSignalDuringPreHookEndsShell()
{
    skip_if_rpm_testing_off && return

    build hooka
    build hookb

    for sig_rc in TERM:143 QUIT:131; do
        sig=${sig_rc%:*}
        rm -f $HOOKS_LOG
        printf '#!/bin/sh\necho pre >> %s\nkill -%s $PPID\n' "$HOOKS_LOG" $sig \
            > $HOOKS/pre-install.d/log

        printf 'install hooka\ninstall hookb\n' | timeout 60 script -qec \
            "ulimit -c 0; $POLDEK_HOOKS -Ouse_sudo=n --shell" /dev/null >/dev/null 2>&1
        rc=$?
        assertEquals "$sig: exit code" "${sig_rc#*:}" "$rc"
        assertEquals "$sig: ran: '$(runs)'" "pre post" "$(runs)"
    done
}

# in poldek's shell a second SIGTERM after one from a pre-install hook ends
# poldek at once, here in a post-install hook; after one that came while rpm
# ran, a second one lets the post-install hooks run to their end
testShellSecondSignalEndsAtOnceUnlessRpmRan()
{
    skip_if_rpm_testing_off && return

    build hooka
    build hookb
    printf '#!/bin/sh\necho post >> %s\nkill -TERM $PPID\nsleep 1\n' "$HOOKS_LOG" \
        > $HOOKS/post-install.d/log
    hook post-install.d log2 post2

    for case in pre-hook rpm; do
        rm -f $HOOKS_LOG
        if [ $case = pre-hook ]; then
            printf '#!/bin/sh\necho pre >> %s\nkill -TERM $PPID\n' "$HOOKS_LOG" \
                > $HOOKS/pre-install.d/log
            expected="pre post"
        else
            hook pre-install.d log pre
            printf '#!/bin/sh\necho rpm >> %s\nkill -TERM $PPID\nsleep 1\n' "$HOOKS_LOG" \
                > $FAKE_RPM
            expected="pre rpm post post2"
        fi

        printf 'install hooka\ninstall hookb\n' | timeout 60 script -qec \
            "ulimit -c 0; $POLDEK_HOOKS -Ouse_sudo=n --shell" /dev/null >/dev/null 2>&1
        rc=$?
        assertEquals "$case: exit code" "143" "$rc"
        assertEquals "$case: ran: '$(runs)'" "$expected" "$(runs)"
    done
}

testHookOutputLineByLine()
{
    skip_if_rpm_testing_off && return

    local log=$TMPDIR/hooks-poldek.log line out

    build hooka
    # the last line with no newline
    printf '#!/bin/sh\nprintf "one\\ntwo"\n' > $HOOKS/post-install.d/a-out
    printf '#!/bin/sh\necho three\n' > $HOOKS/post-install.d/b-out
    chmod 755 $HOOKS/post-install.d/a-out $HOOKS/post-install.d/b-out
    rm -f $log

    out=$($POLDEK_HOOKS -uv hooka --log=$log 2>&1)
    assertEquals "install failed" "0" "$?"
    echo "$out"
    assertEquals "'two' not a line of the output" "1" "$(echo "$out" | grep -c '^two$')"
    for line in "a-out: one" "a-out: two" "b-out: three"; do
        assertEquals "'$line' not a line of the log" "1" "$(grep -c " $line\$" $log)"
    done
}

testMissingPreInstallDirMeansNoPreHooks()
{
    skip_if_rpm_testing_off && return

    build hooka
    rm -rf $HOOKS/pre-install.d

    $POLDEK_HOOKS -uv hooka
    assertEquals "install failed" "0" "$?"
    assertRuns "rpm post"
}

testUnreadablePreInstallDirStopsOperation()
{
    skip_if_rpm_testing_off && return

    build hooka
    rm -rf $HOOKS/pre-install.d
    touch $HOOKS/pre-install.d

    $POLDEK_HOOKS -uv hooka
    rc=$?
    assertTrue "install expected to fail" "[ $rc -ne 0 ]"
    assertRuns ""
}

testMissingHooksDirIsReported()
{
    skip_if_rpm_testing_off && return

    build hooka

    out=$($POLDEK_ON_ROOT -Ohooks_dir=$TMPDIR/no-hooks -uv hooka 2>&1)
    assertEquals "install failed" "0" "$?"
    assertRuns "rpm"
    echo "$out" | grep -q "$TMPDIR/no-hooks"
    assertEquals "missing hooks dir not reported: $out" "0" "$?"
}

testNoHooksWithoutHooksDir()
{
    skip_if_rpm_testing_off && return

    build hooka

    $POLDEK_ON_ROOT -uv hooka
    assertEquals "install failed" "0" "$?"
    assertRuns "rpm"
}

testNoHooksInRpmTestRun()
{
    skip_if_rpm_testing_off && return

    build hooka

    $POLDEK_HOOKS -uv -tt hooka
    assertEquals "test run failed" "0" "$?"
    assertRuns "rpm"
}

testNoHooksWithAnotherRoot()
{
    skip_if_rpm_testing_off && return

    build hooka
    # provide /bin/sh auto requirement
    rpm_build_installed sh -p /bin/sh

    $POLDEK_INSTALL -Ohooks_dir=$HOOKS -uv hooka
    assertEquals "install failed" "0" "$?"
    assertRuns ""
    rpm_state_check "hooka" ""
}

. ./sh/lib/shunit2
