#!@PREFIX@/bin/bash

#==============================================================================
# Stub script, which initiates update via touch
#
# Author: Christopher Nielsen @ MacPorts
#
# Usage:
#   update-mime-database <mime_path>
#   or
#   update-mime-database -v
#==============================================================================

dir_prefix="@PREFIX@"
dir_bin="${dir_prefix}/bin"
dir_mime="${dir_prefix}/share/mime"
dir_mime_pkgs="${dir_mime}/packages"
bin_grealpath="${dir_bin}/grealpath"
bin_update_mime_db="${dir_bin}/@SCRIPT_REAL@"

arg_count=${#}
if [[ ${arg_count} < 1 ]]; then
    printf "Usage: ${0} mime_path\n"
    exit 1
fi

# If '-v' specified, version wanted; defer to real binary
if [[ (${arg_count} == 1) && ("${1}" == "-v") ]]; then
    exec "${bin_update_mime_db}" -v
fi

# mime_path must be last argument; ignore previous args, if any, like -V
arg_path="${@: -1}"

# If last arg starts with '-', it's invalid
if [[ ${arg_path:0:1} == "-" ]]; then
    printf "${0}: mime_path not valid: ${arg_path}\n"
    exit 1
fi

arg_path_full="$(${bin_grealpath} -q ${arg_path})"
if [[ $? != 0 ]]; then
    printf "${0}: mime_path does not exist: ${arg_path}\n"
    exit 1
fi

dir_mime_full="$(${bin_grealpath} -q ${dir_mime})"
if [[ $? != 0 ]]; then
    printf "${0}: dir_mime does not exist: ${dir_mime}\n"
    exit 1
fi

if [[ "${arg_path_full}" == "${dir_mime_full}"* ]]; then
    touch "${dir_mime_pkgs}"
else
    printf "${0}: mime_path does not match ${dir_mime}; ignoring: ${arg_path}\n"
fi

exit 0

