#!/bin/sh
#
# Container machine init script — replaces /sbin/init as the first process (PID 1)
# executed when a container machine boots. Performs container machine-specific setup
# before handing off to the real system init:
#
#   1. Open a user shell when invoked with the "-s" flag.
#      Looks up the current user's shell from /etc/passwd and execs into it,
#      falling back to /bin/sh. If additional arguments follow "-s", runs them
#      as a command via "<shell> -c <args>" instead of dropping into an
#      interactive session.
#
#   2. Boot the system when invoked with no flags.
#      Sets the hostname to CONTAINER_MACHINE_ID and execs /sbin/init to hand
#      off to the real system init.
#
# User setup no longer happens here — it's run by the host directly on every
# boot as a separate exec (see MachineUserSetup.swift), before this script's
# "-s" or default path is invoked.

set -e

if [ "$1" = "-s" ]; then
    shift
    USER_SHELL=$(grep "^$(id -un):" /etc/passwd 2>/dev/null | cut -d: -f7)
    if [ $# -gt 0 ]; then
        exec "${USER_SHELL:-/bin/sh}" -c "$*"
    else
        exec "${USER_SHELL:-/bin/sh}"
    fi
else
    echo "${CONTAINER_MACHINE_ID}" > /etc/hostname

    if [ -S ${SSH_AUTH_SOCK} ]; then
        chown ${CONTAINER_UID}:${CONTAINER_GID} ${SSH_AUTH_SOCK}
    fi

    exec /sbin/init
fi
