#!/bin/bash
set -e
. tests/lib

t-dependencies git-debpush netcat-openbsd autopkgtest
t-restrict x-tag2upload-service-manager

t-debpolicy

t-t2u-native-prep

#---------- start the tag2upload-service-manager daemon ----------

mkdir ../t2usm
cd ../t2usm

mkdir tmp

cat >t2usm.toml <<END

    [rocket]
    log_level = "debug"
    cli_colors = false
    port = 0

    [t2u]
    distro = "debian"

    [log]
    level = "trace"

    [vhosts]
    ui = ["*"]
    webhook = ["*"]

    [files]
    db = "t2usm.db"
    scratch_dir = "tmp"
    o2m_socket = "o2m.s"
    port_report_file = "port"
    archive_dir = "t2usm-archive"

    [timeouts]
    socket_stat_interval = "30 s"

    [[t2u.forges]]
    kind = "gitlab"
    host = "salsa.debian.org"
    allow = ["*"]

END

# We have two independent ways of trying to ensure
# that the t2usm process doesn't outlive this script.
#   1. end_kill_pids
#   2. It will state `o2m_socket` every `socket_stat_interval`.
#      Since that's a relative path, if this directory is removed,
#      it will get ENOENT and quit - even if a new directory
#      with the same name is created.

mkdir t2usm-archive

t-mkfifo port
exec 3<>port
# we pass O_RDWR fd to t2usm; that way we get EOF if it crashes

$DGIT_TEST_T2USM_PROGRAM -c t2usm.toml &
t2usm_pid=$!
end_kill_pids+=" $! "

# we don't keep the O_RDWR fd, only an O_RDONLY one
exec 4<port
exec 3<&-
read <&4 port

cd ..

t-mkfifo check-for-banner
exec 3<>check-for-banner
nc.openbsd -U t2usm/o2m.s >check-for-banner &
exec 3<&-
read banner <check-for-banner

test "$banner" = "t2u-manager-ready"

#---------- start the tag2upload oracle daemon ----------

t-t2u-start-t2u-oracled 					\
    --no-restart-workers

#---------- make an upload tag and push it to pretend-salsa ----------

cd $p

t-t2u-settings

${DGIT_DEBPUSH_TEST-git debpush} --distro=test-dummy -u Senatus "$@"

#---------- simulate webhook ----------

# TODO Diziet
# Convert the tag to a webhook payload that looks roughly like a gitlab one.
# Make the actual webhook http request.
# Check that the http request gave us a good message with a job id.

#---------- await completion and check it worked ----------

# TODO Diziet
# Check that
#   - t-pushed-good
#   - t2usm web page lists job as completed
#   - git tag in dgit-repos is the original one from git-debpush

#---------- success ----------

t-ok
