#!/bin/bash -e

show_help() {
    echo "usage: user-state remove-with-group <user>"
    echo "usage: user-state list-users"
    echo "usage: user-state list-groups"
    echo ""
    echo "The tool is used to manage users and groups."
}

remove_with_group() {
    USER=$1
    if [ -z "$USER" ]; then
        echo "user-state: user is a required parameter"
        exit 1
    fi

    if getent passwd "$USER"; then
        if [ -f /var/lib/extrausers/passwd ]; then
            userdel --extrausers --force --remove "$USER"
        else
            userdel --force --remove "$USER"
        fi
        if getent passwd "$USER"; then
            echo "user-state: user exists after removal"
            exit 1
        fi
    fi

    if getent group "$USER"; then
        if groupdel -h | grep -q force; then
            groupdel -f "$USER"
        else
            groupdel "$USER"
        fi
        if getent group "$USER"; then
            echo "user-state: group exists after removal"
            exit 1
        fi
    fi
}

list_users() {
    getent passwd | cut -d: -f1
}

list_groups () {
    getent group | cut -d: -f1
}

main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi

    local subcommand="$1"
    local action=

    case "$1" in
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            action=$(echo "$subcommand" | tr '-' '_')
            shift
            ;;
    esac

    if [ -z "$(declare -f "$action")" ]; then
        echo "user-state: no such command: $subcommand"
        show_help
        exit 1
    fi

    "$action" "$@"
}

main "$@"