#!/bin/bash
export TEXTDOMAIN=epmgpi
export TEXTDOMAINDIR=/usr/share/locale

gtxt() {
    gettext "$@"
}

if [ $(id -u) -eq 0 ]; then
  gtxt "epmgpi cannot be run as root user."
  exit 1
fi

# Temporary files
clean_up_tmp() {
  rm -fr "$EPMGPI_TMP"
}

EPMGPI_TMP=$(mktemp -d -t epmgpi.XXXXXXX)
trap "clean_up_tmp $EPMGPI_TMP" EXIT

EPMGPI_LOG_FILE="$EPMGPI_TMP/epmgpi.log"

# Default yad parameters
YAD_DEFAULT="/usr/bin/yad --window-icon=epmgpi --title=epmgpi --class=epmgpi"

VALID_FILE_EXTENSIONS=(
    "*.rpm" "*.deb" "*.run"
    "*.appimage" "*.AppImage" "*.Appimage"
)

check_extension() {
    local FILE="$1"
    for EXT in "${VALID_FILE_EXTENSIONS[@]}"; do
        if [[ "$FILE" == $EXT ]]; then
            return 0
        fi
    done
    return 1
}

# Notifications
ntf() {
    notify-send --icon=epmgpi "$1"
}

# Error notification
ntf_error() {
    notify-send  --icon=error "$1"
}

file_exec_warn() {
    local NEED_RULES

    if [ -x "$1" ]; then
        NEED_RULES=False
    else
        NEED_RULES=True
    fi

    $YAD_DEFAULT --image="dialog-warning" \
    \
    --width=500 --height=200 \
    --text="$(
    gtxt \
    "epmgpi has detected that you are running a file.
Launching extraneous files can lead to unforeseen consequences."
    echo
    echo
    if [ "$NEED_RULES" = True ]; then
        gtxt "Additionally, the file needs execute permissions.

Do you want to grant the file execute permissions and run it?"
    else
        gtxt "Do you really want to run the file?"
    fi
    )" \
        --button="yad-yes:0" \
        --button="yad-no:1"
      
        local ANSWER=$?

        if [[ $ANSWER -eq 0 ]]; then
            if [ "$NEED_RULES" = True ]; then
                chmod +x "$1"
            fi
            exec "$1"
        fi
}

# Function to ask the user if the package should be repacked
repackq() {
    # Non-rpm files are repacked without --repack key
    if [[ $PKG_PATH == *.rpm ]]; then
        $YAD_DEFAULT --image="dialog-question" --text="$(gtxt "Do you want to repack the rpm file to override dependencies?")" \
      --button="yad-yes:0" \
      --button="yad-no:1"
      
        local ANSWER=$?

        if [[ $ANSWER -eq 0 ]]; then
            local EEPM_ARGS="--auto --repack -i"
        else
            local EEPM_ARGS="--auto -i"
        fi
    else
        local EEPM_ARGS="--auto -i"
    fi
    echo "$EEPM_ARGS"
}

# GUI package selector
pkgselection() {
    $YAD_DEFAULT --file --file-filter="${VALID_FILE_EXTENSIONS[*]}"
}

yad_log_view() {
    $YAD_DEFAULT --title="$(gtxt "Error Log")" --no-buttons --text-align=center \
    --text-info --show-uri --wrap --width=1200 --height=550 --uri-color=red \
    --filename="$EPMGPI_LOG_FILE"
    rm "$EPMGPI_LOG_FILE"
    exit 1
}

epmgpi_logging() {
    tee -a "$EPMGPI_LOG_FILE"
}

# Check if the file is a package
hack_for_paths_with_spaces() {
    PKG_PATH="$1"
    local PKG_NAME
    PKG_NAME=$(basename -- "$PKG_PATH" | tr -d ' ')
    local PKG_SYMB_LINK_PATH="$EPMGPI_TMP/$PKG_NAME"
    ln -s "$PKG_PATH" "$PKG_SYMB_LINK_PATH"
    echo "$PKG_SYMB_LINK_PATH"
}

# Install package
installpkg() {
    local PKG_PATH="$1"
    local EEPM_ARGS="$2"
    # Pkexec for executing as root
    (
        /usr/bin/pkexec /usr/bin/epm $EEPM_ARGS "$PKG_PATH" 2>&1
        exit_code=$?

        case $exit_code in
            0)
                gtxt "Command completed successfully"
                echo
                ntf "$(gtxt "Package installed!")"
                exit 0
                ;;
            100)
                ntf_error "$(gtxt "Package not installed. Command failed.")"
                echo "!!! EPMGPI ERROR" >> "$EPMGPI_LOG_FILE"
                ;;

            126)
                ntf_error "$(gtxt "Package not installed. Action canceled by the user.")"
                exit 1
                ;;
            *)
                ntf_error "$(gtxt "Package not installed.")"
                echo "!!! EPMGPI ERROR" >> "$EPMGPI_LOG_FILE"
                ;;
        esac
    
    ) | epmgpi_logging | sed -u 's/^/# /' | $YAD_DEFAULT \
    --title="$(gtxt "Package Installation")" \
    --progress --width=800 --height=500 \
    --enable-log="$(gtxt "Log")" --log-expanded --log-on-top \
    --auto-kill --auto-close
}

show_help() {
    gtxt "Usage: epmgpi [option] [path-to-package]"
    echo
    gtxt "Options:"
    echo
    gtxt "  --help, -h       Show this help"
    echo
    gtxt "  --version, -v    Show version information"
    echo
    gtxt "Pass the path to the package if you don't want to use the file selection dialog."
    echo
}

main() {
    local PKG_PATH
    local FILE_PATH
    FILE_PATH="$1"
    # Check and call file selection dialog if PKG_PATH is not set
    if [[ -z "$FILE_PATH" ]]; then
        gtxt "Package path not specified. Calling package selection function..."
        FILE_PATH=$(pkgselection)
    fi
    
    if [ ! -f "$FILE_PATH" ]; then
        printf "$(gtxt "Error: %s is not a file.")\n" "$FILE_PATH"
        exit 1
    fi
    
    if ! check_extension "$FILE_PATH"; then
        file_exec_warn "$FILE_PATH"
        exit 0
    fi
    
    if echo "$FILE_PATH" | grep -q " "; then
        gtxt "Package path contains spaces"
        echo
        PKG_PATH=$(hack_for_paths_with_spaces "$FILE_PATH")
    else
        PKG_PATH=$FILE_PATH
    fi

    installpkg "$PKG_PATH" "$(repackq)"

    if grep -q "!!! EPMGPI ERROR" "$EPMGPI_LOG_FILE" ; then
        yad_log_view
    fi
}

if [[ $# -eq 0 ]]; then
    main | epmgpi_logging
else
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --help|-h)
                show_help
                exit 0
                ;;
            --version|-v)
                gtxt "Version:"
                echo " 1.5.1"
                exit 0
                ;;
            *)
                printf "$(gtxt "Arguments passed: %s")\n" "$1"
                main "$(realpath "$1")" | epmgpi_logging
                shift
                ;;
        esac
    done
fi
