#!/usr/bin/execlineb

##
## dump environment into files and a bash script
##

# base for file and path
define contenvsdir /etc/container_environment

# assure folder does exist
foreground { mkdir -p ${contenvsdir} }

foreground {
  forbacktickx i {
    pipeline { s6-env } s6-cut -d"=" -f1
  }
  import i import ${i}
  foreground {
    redirfd -w 1 ${contenvsdir}/${i}
    s6-echo ${${i}}
  }
}

##
## fix attributes (ownership and permissions)
##

foreground { s6-echo "[fix-attrs] fixing file attributes (ownership & permission)..." }
foreground {
  forbacktickx i {
    find /etc/fix-attrs.d -maxdepth 1 -type f ! -name ".*" ! -path /etc/fix-attrs.d
  }
  import i
  foreground { s6-echo "[fix-attrs] ${i}: applying..." }
  foreground { fix-attrs fix ${i} }
  foreground { s6-echo "[fix-attrs] ${i}: done." }
}
foreground { s6-echo "[fix-attrs] done." }

# i don't know why but, it seems like 'fix-attrs' is not freeing file
# handles and therefore files which were accesed/modified cannot be used
# for execution. We flush all the dirty system buffers, and blocks until 
# they're clean.
foreground { s6-sync }

##
## fork the "init-stage2" script
##

background
{
  elgetpositionals
  /etc/s6/.s6-init/init-stage2 $@
}
unexport !

# start stage 2.
s6-envdir ${contenvsdir}
s6-svscan -t0 /etc/s6
