#!/bin/execlineb -S0

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

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

# This env decides if we should call s6-sync or not (default no)
backtick -D 0 -n S6_SYNC_DISKS { printcontenv S6_SYNC_DISKS }
importas -u S6_SYNC_DISKS S6_SYNC_DISKS

# 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."
  }
}

# Wait service down

foreground { s6-echo "[s6-finish] waiting for services." }
foreground
{
  backtick -D 3000 -n S6_SERVICES_GRACETIME { printcontenv S6_SERVICES_GRACETIME }
  importas -u S6_SERVICES_GRACETIME S6_SERVICES_GRACETIME
  elglob SERVICES /var/run/s6/services/*
  foreground { s6-svwait -D -t ${S6_SERVICES_GRACETIME} ${SERVICES} }
  s6-sleep -m 200
}

# Sync before TERM'n
foreground
{
  if { s6-test ${S6_SYNC_DISKS} -eq 1 }
    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
{
  if { s6-test ${S6_SYNC_DISKS} -eq 1 }
    s6-sync
}


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

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