#!/bin/bash
# dib-lint: disable=executable

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

function firstboot_common {
    distro=$(lsb_release -is || :)
    RUNDIR=/run
    if [ ! -d $RUNDIR ]; then
        RUNDIR=/var/run
    fi
    case "$distro" in
        Ubuntu )
            mkdir -p /home/ubuntu/.ssh
            touch /home/ubuntu/.ssh/authorized_keys
            chown -R ubuntu:ubuntu /home/ubuntu
        ;;
        Fedora )
            sleep 20
            rm /etc/resolv.conf
            service network restart
            if [ $(lsb_release -rs) -ge '19' ]; then
                user=fedora
            else
                user=ec2-user
            fi
            until [[ -n $(grep "$user:" /etc/passwd) && -n $(grep "$user:" /etc/group) ]]; do
                sleep 1
            done
            chown -R $user:$user /home/$user
        ;;
        CentOS )
            case "$(lsb_release -rs)" in
                7.*)
                    chown -R centos:centos /home/centos
                    ;;
            esac
        ;;
        * )
            echo "Unknown distro: $distro. Exiting."
            exit 1
        ;;
    esac

    mkdir -p /mnt/log/hadoop
    chown hadoop:hadoop /mnt/log/hadoop

    mkdir -p $RUNDIR/hadoop
    chown hadoop:hadoop $RUNDIR/hadoop
}

DIB_HADOOP_VERSION=$(su - hadoop hadoop version | head -1 | awk '{print $2}')

firstboot_common

# Clean
if [ "$distro" == "Ubuntu" ]; then
    if [ -f /etc/rc.local.old ]; then
        mv /etc/rc.local.old /etc/rc.local
    fi
else
    if [ -f /etc/rc.d/rc.local.old ]; then
        mv /etc/rc.d/rc.local.old /etc/rc.d/rc.local
    fi
fi

exit 0
