#!/bin/bash

# By default, this file is /root/osbashauto (with systemd) or
# /etc/init.d/osbashauto (for sysvinit) on the guest system.
# On boot-up, it executes in order all files that have been put into
# the autostart folder.

# The name of this file is hard-coded in activate_autostart.sh.

SHARE_NAME=%SHARE_NAME%

# Make sure we have a mount point for the shared directory
mkdir -p /$SHARE_NAME

# Wait for mountpoint to become available (keep log file so we can copy it to
# the share once it is mounted)
SHARE_MOUNT_LOG=share_mount.log
while ! mountpoint -q /$SHARE_NAME; do
    if mount -t vboxsf -ouid=%VM_SHELL_USER%,gid=%VM_SHELL_USER% $SHARE_NAME /$SHARE_NAME; then
        echo "$(date) Mounting succeeded!" >> /tmp/$SHARE_MOUNT_LOG
    else
        echo "$(date) Mounting failed, trying again." >> /tmp/$SHARE_MOUNT_LOG
    fi
    sleep 1
done

# LOG_DIR is set in activate_autostart.sh as NLOG_DIR
LOG_DIR=%NLOG_DIR%

# Save share mount log for all reboots in one file
cat /tmp/$SHARE_MOUNT_LOG >> "$LOG_DIR/$SHARE_MOUNT_LOG"

STATUS_DIR=%NLOG_DIR%/status

mkdir -p $STATUS_DIR

TOP_DIR=/$SHARE_NAME

source "$TOP_DIR/config/paths"
source "$LIB_DIR/functions.guest.sh"

exec_logpath "$LOG_DIR/%RCAUTOSTART%.log"

echo "$(date) starting"

shopt -s nullglob
for AUTODIR in "/$SHARE_NAME/autostart" "/$SHARE_NAME/autostart/$HOSTNAME"; do
    if [ -d "$AUTODIR" ]; then
        echo "$(date) autodir $AUTODIR"
        for SCRIPT in $AUTODIR/*.sh; do
            if ! as_root_exec_script "$SCRIPT"; then
                echo >&2 "Script returned with error, giving up."
                # Tell host about the error
                echo "ERROR in $SCRIPT" >> "$STATUS_DIR/error"
                exit 1
            fi
            # Remove script after execution
            rm "$SCRIPT"
        done
    fi
done

echo "$(date) autostart done"

# This file is seen and removed by scripts running on the host
touch "$STATUS_DIR/done"

exit 0

# vim: set ai ts=4 sw=4 et:
