#!/bin/bash
# hostsfilemods - GENERATE HOSTS FILE MODIFICATION ENTRIES
# WRITTEN BY: Joe Cartonia
# LAST MODIFIED: 2016-06-30 - DanielK

function display_help
{
    echo
    echo "hostsfilemods: Displays hosts file modification entries."
    echo "USAGE: hostsfilemods <username>"
    echo "-h | --help            Show usage information and exit"
    echo "-a | --all-users       Generate entries for all user domains"
    echo "-l | --list-users      List all cPanel usernames"
    echo "-s | --separate-line   Print even www. subdomains on a separate line"
    echo "-r | --reseller        Include hosts for accounts owner by the specified reseller"
    echo
    exit
}

# Parse options:
show_help=0
all_users=0
list_users=0
include_children=0
separate_line=0
user_array=()
for i in "$@"
do
    case $i in
        -h | --help)       show_help=1 ;;
        -a | --all-users)  all_users=1; users="" ;;
        -l | --list-users) list_users=1; break ;;
        -s | --separate-line) separate_line=1; ;;
        -r | --reseller)   include_children=1; ;;
        [a-z]*|[0-9]*)     user_array+=("$i")
    esac
    if [[ "$show_help" -eq 1 ]] ;then display_help; fi
done
unset i


# Usage check:
if [[ -z "$1" ]] ;then
    display_help
fi


# List all users:
if [[ "$list_users" -eq 1 ]] ; then
    cat /etc/trueuserowners | awk -F':' '$0!~"#"{print $1}'
    exit
fi


# Add child accounts if requested
if [[ "$include_children" -eq 1 ]] ;then
    for reseller in "${user_array[@]}"; do
        while read user_file; do
            user="$(basename "$user_file")"
            [[ -n "$user" ]] && user_array+=("$user")
        done < <(cat /etc/trueuserowners | awk -F': ' -v reseller="$reseller" '$2~reseller{print $1}')
    done
    unset reseller
fi


# User check:
if [[ "$all_users" -eq 1 ]] ; then
    while read user ; do
        user_array+=("$user");
    done < <(cat /etc/trueuserowners | awk -F': ' 'NF==2{print $1}')
elif [[ -z "$user_array" ]] ; then
    echo "Error: No user(s) specified!"
    display_help
fi
unset all_users


# Remove duplicate entries
user_array=($(printf "%q\n" "${user_array[@]}" | sort -u))


# Generate hosts file modification entries:
for user in "${user_array[@]}"
do
    [[ -f "/var/cpanel/users/$user" ]] || continue
    for ip in $(sudo cat "/var/cpanel/users/$user" | awk -F= '/^IP=/{print $2}')
    do
      	for domain in $(sudo cat "/var/cpanel/users/$user" | awk -F= '/^DNS/{print $2}' | sort)
        do
            if [[ "$separate_line" -eq 1 ]] ;then
                echo -e "$ip\t$domain"
                echo -e "$ip\twww.$domain"
            else
                echo -e "$ip\t$domain www.$domain"
            fi
        done
        unset domain
    done
    unset ip
done
unset user_array
