##
## Copyright 2014 Cumulus Networks Inc.
## All rights reserved
##
## Useful image upgrade functions and variables for boot time.
##
## This assumes the shell is ash/dash.
##

upgrade_marker="var/lib/cumulus/installer/upgrade"

find_files()
{
    # Find files excluding paths
    local spath="${1%/}"
    shift
    local path_exclude="$*"
    local prune_paths
    for p in $path_exclude
    do
        local _dir=${p#"/"}
        local _p="-path ${spath}/${_dir}"
        [ -z "$prune_paths" ] && {
            prune_paths=$_p
            continue
        }
        prune_paths="$_p -o ${prune_paths}"
    done
    find "$spath" \( $prune_paths \) -prune -o -type f -print
}

list_installed_pkgs_in()
{
    local root=$1
    chroot "$root" dpkg-query -W -f='${Package}\n' > "$2"
}

file_in_package()
{
    # Return packge name file belongs to
    local __result=$(chroot "$1" dpkg -S "$2" 2>/dev/null | grep '^\S*:' | cut -d ':' -f1)
    echo -n "$__result"
}

bury_copy()
{
    mkdir -p "$(dirname $2)" && cp -p "$1" "$2"
}

upgrade_reinstall_packages()
{
    local _pkgs="$1"
    local _sysroot="$2"
    local _sysroot_old_mnt="$3"

    echo "# Reinstall previously installed packages ..."

    if [ -n "${_pkgs}" ] ; then
        local inst_opts="dpkg -i --refuse-downgrade --force-depends"
        echo -e "Packages to be installed:\n${_pkgs}"
        echo ${_pkgs} | chroot $_sysroot xargs dpkg-repack --root=${_sysroot_old_mnt}
        chroot $_sysroot /bin/sh -c "${inst_opts} *.deb"
        chroot $_sysroot /bin/sh -c "rm -f *.deb"
    fi
}
