#!/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/>.

# Enter the name of the toolbox to search for your commands in here, or in the
# config file `cnf.conf`.
TOOLBOX_NAME=""

# Return 0 if we run in a toolbox
function is_toolbox {
    [[ -f "/run/.toolboxenv" ]]
    return $?
}

# Check if we're running in a toolbox
if is_toolbox; then
    # Forward the command to the host
    if command -v flatpak-spawn 1>/dev/null; then
        # Sudo needs special handling to read password from stdin
        # Injecting '-S' argument to request user password through stdin
        if [[ $1 = sudo ]]; then
            set -- "${@:1:1}" "-S" "${@:2}"
        fi

        echo "Running command '$1' on the host"
        flatpak-spawn --host "$@"
        exit $?
    fi
else
    # Load config file. Currently only contains TOOLBOX_NAME
    if [[ -f "$HOME/.config/cnf.conf" ]]; then
        . $HOME/.config/cnf.conf
    fi

    if command -v toolbox 1>/dev/null; then
        if [[ -z $TOOLBOX_NAME ]]; then
            echo "Running command '$1' in default toolbox"
            toolbox run "$@"
        else
            echo "Running command '$1' in toolbox '$TOOLBOX_NAME'"
            toolbox run -c $TOOLBOX_NAME "$@"
        fi

        exit $?
    fi
fi

echo "$1: command not found"
exit 127
