#!/usr/bin/env bash

function main() {
    local vboxGroupName="vboxsf"
    local scriptdir="$(dirname "$(readlink -f "$0")")"
    local logLocation="${scriptdir}/guest_additions_log_$(date +%s).log"
    local mountLocation="/mnt/vm"

    printf "Check script is run as root..." | tee -a "${logLocation}"
    if [ "$(id -u)" -eq 0 ]
    then
        printf "Done!\n" | tee -a "${logLocation}"
    else
        printf "\n\nERROR: Script must be run as root\n" | tee -a "${logLocation}"
        return 1
    fi

    printf "\nCreate mount directory..." | tee -a "${logLocation}"
    if mkdir "${mountLocation}" &>> "${logLocation}"
    then
        printf "Done!\n" | tee -a "${logLocation}"
    else
        printf "\n\nERROR: Failed to create mount directory \"%s\"\n" "${mountLocation}" | tee -a "${logLocation}"
        return 1
    fi

    printf "\nInstall virtualbox guest additions..." | tee -a "${logLocation}"
    if apt-get install -y virtualbox-guest-utils virtualbox-guest-dkms virtualbox-guest-x11 &>> "${logLocation}"
    then
        printf "Done!\n" | tee -a "${logLocation}"
    else
        printf "\n\nERROR: Failed to install virtualbox guest additions\n" | tee -a "${logLocation}"
        return 1
    fi

    ls -c1 "/home/" | while read -r username ; do
        printf "\nAdd user \"%s\" to virtualbox group..." "${username}" | tee -a "${logLocation}"
        if usermod -a -G "${vboxGroupName}" "${username}" &>> "${logLocation}"
        then
            printf "Done!\n" | tee -a "${logLocation}"
        else
            printf "\n\nERROR: Failed to add user \"%s\" to group \"%s\"" "${username}\n" "${vboxGroupName}" | tee -a "${logLocation}"
            return 1
        fi
    done

    printf "\nGuest additions set up successfully!\n" | tee -a "${logLocation}"

    return 0
}

main "$@"
