#!/bin/bash

#   CNF - A "command-not-found" for toolbx users
#   Copyright (C) 2022  Andreas Hartmann <hartan@7x.de>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.

## Custom sudo override
# If it doesn't find a command in roots $PATH, forwards it to CNF instead, if
# present.

cmd=""
for arg in "$@"; do
    case $arg in
        -*)
            ;;
        *) 
            cmd=$arg; 
            break;;
    esac
done

# Check if command exists for root
if [[ -z $cmd ]]; then
    # No command given?
    /usr/bin/sudo "$@";
    exit $?;
fi

if $(/usr/bin/sudo command -v "$cmd" 2>/dev/null 1>&2); then
    /usr/bin/sudo "$@";
    exit $?;
else
    # Command doesn't exist for user root. Forward to CNF
    if $(command -v 2>/dev/null 1>&2); then
        cnf "sudo" "$@"
    fi
    exit $?
fi

exit 2

