#!/usr/bin/execlineb -S0

# This is the shutdown script, running as process 1.
cd /

# Merge environments from our custom stage into current context
s6-envdir -I /var/run/s6/env-stage3

# cont-finish.d: one-time finish scripts

foreground
{
  backtick -D 5000 -n S6_KILL_FINISH_MAXTIME { printcontenv S6_KILL_FINISH_MAXTIME }
  importas -u S6_KILL_FINISH_MAXTIME S6_KILL_FINISH_MAXTIME
  if
  {
    if -t { s6-test -d /var/run/s6/etc/cont-finish.d }
    if { s6-echo "[cont-finish.d] executing container finish scripts..." }
    if
    {
      pipeline { s6-ls -0 -- /var/run/s6/etc/cont-finish.d }
      pipeline { s6-sort -0 -- }
      forstdin -o 0 -0 -- i
      importas -u i i
      if { s6-echo -- "[cont-finish.d] ${i}: executing... " }
      foreground
      {
        s6-maximumtime -k ${S6_KILL_FINISH_MAXTIME}
        /var/run/s6/etc/cont-finish.d/${i}
      }
      importas -u ? ?
      s6-echo -- "[cont-finish.d] ${i}: exited ${?}."
    }
    s6-echo -- "[cont-finish.d] done."
  }
}


# Sync before TERM'n

foreground { s6-echo "[s6-finish] syncing disks." }
foreground { s6-sync }


# Kill everything, gently.

foreground { s6-echo "[s6-finish] sending all processes the TERM signal." }
foreground { s6-nuke -th } # foreground is process 1: it survives
foreground
{

  backtick -D 3000 -n S6_KILL_GRACETIME { printcontenv S6_KILL_GRACETIME }
  importas -u S6_KILL_GRACETIME S6_KILL_GRACETIME
  s6-sleep -m -- ${S6_KILL_GRACETIME}
}

# Last message, then close our pipes and give the logger some time.
foreground { s6-echo "[s6-finish] sending all processes the KILL signal and exiting." }
fdclose 1 fdclose 2
s6-sleep -m 200


# Kill everything, brutally.

foreground { s6-nuke -k } # foreground is process 1: it survives again


# Reap all the zombies then sync, and we're done.

wait { }
foreground { s6-sync }


# Use CMD exit code defaulting to zero if not present.

importas -u -D0 S6_CMD_EXITED S6_CMD_EXITED
exit ${S6_CMD_EXITED}
