#!/bin/bash

## Copyright (C) 2025 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## TODO: document

set -x
set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

container=docker
export container

if [ $# -eq 0 ]; then
  printf '%s\n' 'ERROR: No command specified. You probably want to run "journalctl -f", or maybe "bash"?' >&2
  exit 1
fi

## SilverMetal patch: TTY check disabled.
##
## Upstream's check exits if stdin isn't a TTY. That's right for an
## interactive `docker run -t ...` invocation by a developer, but in CI
## we cannot allocate a TTY without it making derivative-maker think
## a human is present — at which point any error drops it into an
## interactive `read -p 'Answer? ' answer` prompt and the container
## hangs forever (orphaning the docker run, which orphans the
## act_runner job container, and so on).
##
## Removing the check is safe: nothing downstream actually needs a TTY;
## entrypoint.sh just writes the command and execs systemd.
##
## --- original upstream block (kept commented for the next bump) ---
## if [ ! -t 0 ]; then
##   printf '%s\n' 'ERROR: TTY needs to be enabled ("docker run -t ...").' >&2
##   exit 1
## fi

env | tee -- /etc/docker-entrypoint-env >/dev/null

## Debugging.
cat -- /etc/docker-entrypoint-env

quoted_args="$(printf " %q" "${@}")"
## SilverMetal patch: wrap the command with an explicit redirect to
## /dev/console. systemd's `StandardOutput=inherit` on a service does
## not propagate PID 1's stdout in a containerized PID-1-systemd
## context, so service stdout ends up nowhere visible. With `docker
## run -t`, /dev/console *is* the allocated PTY connected back to
## docker run, so writing there surfaces the build log to the
## act_runner / Gitea Actions log surface.
printf '%s\n' "exec${quoted_args} > /dev/console 2>&1" \
    | tee -- /etc/docker-entrypoint-cmd >/dev/null
chmod +x -- /etc/docker-entrypoint-cmd

systemctl mask systemd-firstboot.service systemd-udevd.service systemd-modules-load.service
systemctl unmask systemd-logind
systemctl enable docker-entrypoint.service

systemd=
if [ -x /lib/systemd/systemd ]; then
  systemd=/lib/systemd/systemd
elif [ -x /usr/lib/systemd/systemd ]; then
  systemd=/usr/lib/systemd/systemd
elif [ -x /sbin/init ]; then
  systemd=/sbin/init
else
  printf '%s\n' 'ERROR: systemd is not installed' >&2
  exit 1
fi

declare -a systemd_args=(
  --show-status=false
  --unit=docker-entrypoint.target
)

printf '%s\n' "$0: starting $systemd ${systemd_args[*]}"

exec "$systemd" "${systemd_args[@]}"
