#!/bin/sh
#
# Copyright (C) 2009, 2012, 2016  Etersoft
# Copyright (C) 2009, 2012, 2016  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# copied from etersoft-build-utils/bin/rpmqf

# TODO: check for lib64/name situations
__abs_filename()
{
    if echo "$1" | grep -q "/" ; then
        echo "$1"
        return
    fi
    if [ -e "$1" ] ; then
        echo "$(pwd)/$1"
        return
    fi
    echo "$1"
}

# work against usrmerge: print the path with resolved dir (/bin/bash -> /usr/bin/bash)
__usrmerge_path()
{
    echo "$(realpath "$(dirname "$1")")/$(basename "$1")"
}

__do_query_file_owner()
{
    if [ -n "$short" ] ; then
        __do_short_query "$1"
    else
        __do_query "$1"
    fi
}

__do_query_real_file()
{
    local TOFILE
    local file="$1"

    # get canonical path (-L for broken symlinks where -e fails)
    if [ -e "$file" ] || [ -L "$file" ] ; then
        TOFILE="$(__abs_filename "$file")"
    else
        TOFILE="$(print_command_path "$file" || echo "$file")"
        if [ "$TOFILE" = "$file" ] ; then
            fatal 'File $TOFILE is missing in $PATH'
        else
            TOFILE="$(__usrmerge_path "$TOFILE")"
            info ' > $file is placed as $TOFILE'
        fi
    fi

    [ -n "$TOFILE" ] || return

    local RES
    __do_query_file_owner "$TOFILE"
    RES=$?

    # dpkg knows only /usr/bin/bash, not /bin/bash
    if [ "$RES" != "0" ] ; then
        local t="$(__usrmerge_path "$TOFILE")"
        if [ "$t" != "$TOFILE" ] ; then
            info ' > $TOFILE is placed as $t'
            TOFILE="$t"
            __do_query_file_owner "$TOFILE"
            RES=$?
        fi
    fi

    # get value of symbolic link
    if [ -L "$TOFILE" ] ; then
        local LINKTO
        LINKTO=$(readlink -- "$TOFILE")
        info " > $TOFILE is link to $LINKTO"
        LINKTO=$(readlink -f -- "$TOFILE")
        if [ -e "$LINKTO" ] ; then
            __do_query_real_file "$LINKTO"
            return
        fi
        return $RES
    else
        return $RES
    fi
}

dpkg_print_name_version()
{
    local ver i
    for i in "$@" ; do
        [ -n "$i" ] || continue
        ver=$(a='' dpkg -s "$i" 2>/dev/null | grep "Version:" | sed -e "s|Version: ||g")
        if [ -z "$ver" ] ; then
            echo "$i"
        else
            echo "$i-$ver"
        fi
    done
}


# print names of packages owning the file from dpkg -S output
# (skip diversions, split "pkg1, pkg2: /path", drop :arch)
__dpkg_file_owners()
{
    local out
    out="$(a='' dpkg -S "$1")" || return
    echo "$out" | grep -v "^diversion by" | sed -e "s|: /.*||" | tr ',' '\n' | sed -e "s|^ *||" -e "s|:.*||"
}

__do_query()
{
    local CMD
    case $PMTYPE in
        *-dpkg)
            showcmd dpkg -S "$1"
            local owners
            owners="$(__dpkg_file_owners "$1")" || return
            dpkg_print_name_version $owners
            return ;;
        *-rpm)
            CMD="rpm -qf"
            ;;
        emerge)
            assure_exists equery
            CMD="equery belongs"
            ;;
        pacman)
            CMD="pacman -Qo"
            ;;
        pkgng)
            CMD="pkg which"
            ;;
        conary)
            CMD="conary query --path"
            ;;
        slackpkg)
            # note: need remove leading slash for grep
            docmd grep -R -- "$(echo $@ | sed -e 's|^/\+||g')" /var/log/packages | sed -e "s|/var/log/packages/||g"
            return
            ;;
        opkg)
            CMD="opkg search"
            ;;
        eopkg)
            CMD="eopkg search-file"
            ;;
        pisi)
            CMD="pisi search-file"
            ;;
        xbps)
            # FIXME: maybe it is search file?
            CMD="xbps-query -o"
            ;;
        aptcyg)
            #CMD="apt-cyg packageof"
            # is not implemented locally
            return 1
            ;;
        *)
            fatal 'Have no suitable query command for $PMTYPE'
            ;;
    esac

    docmd $CMD $@
}


__do_short_query()
{
    local CMD
    case $PMTYPE in
        *-rpm)
            CMD="rpm -qf --queryformat %{NAME}\n"
            ;;
        *-dpkg)
            showcmd dpkg -S "$1"
            __dpkg_file_owners "$1"
            return ;;
        NOemerge)
            assure_exists equery
            CMD="equery belongs"
            ;;
        NOpacman)
            CMD="pacman -Qo"
            ;;
        NOslackpkg)
            # note: need remove leading slash for grep
            docmd grep -R "$(echo $@ | sed -e 's|^/\+||g')" /var/log/packages | sed -e "s|/var/log/packages/||g"
            return
            ;;
        *)
            fatal 'Have no suitable query command for $PMTYPE'
            ;;
    esac

    docmd $CMD $@
}


# print short names of packages owning the file,
# or owning the symlink target if the file itself is not owned (f.i., alternatives)
get_file_owner_packages()
{
    local file="$1" owners t
    owners="$(short=1 __do_short_query "$file" 2>/dev/null)"
    if [ -z "$owners" ] ; then
        t="$(__usrmerge_path "$file")"
        [ "$t" = "$file" ] || owners="$(short=1 __do_short_query "$t" 2>/dev/null)"
    fi
    if [ -z "$owners" ] && [ -L "$file" ] ; then
        t="$(readlink -f -- "$file")"
        [ -e "$t" ] && owners="$(short=1 __do_short_query "$t" 2>/dev/null)"
    fi
    [ -n "$owners" ] || return
    echo "$owners" | sort -u
}

epm_query_file()
{
    # file can exists or not
    [ -n "$*" ] || fatal "Run query without file names"


    #load_helper epm-search_file

    res=0
    for pkg in "$@" ; do
        __do_query_real_file "$pkg" || res=$?
    done

    [ "$res" = "0" ] || info "Try epm sf for search file in all packages of the repositories"
    #|| pkg_filenames="$FULLFILEPATH" epm_search_file
    return $res
}
