#!/bin/bash


sudo_file=/etc/sudoers
sudo_file_bak=/etc/sudoers.bak


# Backup sudoers file
cp ${sudo_file} ${sudo_file_bak}

# Add Command Aliases
add_cmd_alias() {
    {% for sudo in sudo_alias %}
    if $(grep '^Cmnd_Alias {{ sudo.name }}' ${sudo_file} &> /dev/null); then
        sed -i 's@^Cmnd_Alias.*{{ sudo.name }}.*@Cmnd_Alias {{ sudo.name }} = {{ sudo.commands }}@g' ${sudo_file}
    else
        echo "Cmnd_Alias {{ sudo.name }} = {{ sudo.commands }}" >> ${sudo_file}
    fi
    {% endfor %}
}


# Add Command Aliases to role
add_role_chosen() {
    {% for role, sudos in role_chosen_aliase.items %}
        {% for sudo in sudos %}
        if $(grep '^{{ role }}.*{{ sudo.name }}' ${sudo_file} &> /dev/null); then
            sed -i 's@^{{ role }}.*{{ sudo.name }}@{{ role }} ALL = NOPASSWD: {{ sudo.name }}@g' ${sudo_file}
        else
            echo "{{ role }} ALL = NOPASSWD: {{ sudo.name }}"  >> ${sudo_file}
        fi
        {% endfor %}
    {% endfor %}
}

# Check sudoers file configured correctly
check_sudo_file() {
    status=$(visudo -c &> /dev/null && echo "ok" || echo "failed")
    if [ ${status} == "failed" ]; then
        mv ${sudo_file_bak} ${sudo_file}
        ret="failed"
    else
        ret="ok"
    fi
}


add_cmd_alias
add_role_chosen
check_sudo_file

echo ${ret}