#!/bin/bash

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

# We have to chown the Spark directories to make it usable for the default user
# Unfortunately the Ubuntu user does not exists when DIB is creating the image
# and we need to execute this code the first time the VM boots.

firstboot_script_name="/opt/spark/firstboot.sh"
if [ "$DISTRO_NAME" == "ubuntu" ]; then
    sed -i -e "s,^exit 0$,[ -f $firstboot_script_name ] \&\& sh $firstboot_script_name; exit 0," /etc/rc.local
    if [ "$plugin_type" == "vanilla" ]; then
        user_and_group_names="hadoop:hadoop"
    elif [ "$plugin_type" == "spark" ]; then
        user_and_group_names="ubuntu:ubuntu"
    fi
else
    sed -i -e "s,^exit 0$,[ -f $firstboot_script_name ] \&\& sh $firstboot_script_name; exit 0," /etc/rc.d/rc.local
    user_and_group_names="hadoop:hadoop"
fi

cat >> $firstboot_script_name <<EOF
#!/bin/sh
chown -R $user_and_group_names /opt/spark
chown -R $user_and_group_names /etc/hadoop
rm $firstboot_script_name
EOF

