# Idempotent refreshable operations

apply_GETOPTS='pFn'

APPLY=
APPLY_FORCE=
APPLY_DIFF=

function apply_help {
    cat <<END
Apply:
    -p      show changes
    -F      force-updates without checking src mtime
    -n      no-op/mock-update; don't actually change/deploy anything; implies -SpC
END
}

function apply_opt {
    local opt=$1
    local optarg="$2"

    case $opt in
        p)  APPLY_DIFF=1   ;;
        F)  APPLY_FORCE=1  ;;
        
        n) 
            APPLY=0
            APPLY_DIFF=1
        ;;
        *)  return 1
    esac
}

. $LIB/pvl/apply/dir.sh
. $LIB/pvl/apply/link.sh
. $LIB/pvl/apply/cmd.sh
. $LIB/pvl/apply/cat.sh

## Compare the given output file with all given source files:
#
#   check_update $out ${deps[@]} && do_update $out ... || ...
#
# Returns true if the output file needs to be updated.
function apply_check {
    local update=
    local out="$1"

    log_debug           "$out"

    if [ ${#@} -eq 1 ]; then
        log_changed     "  update: empty deps"
        return 2

    elif [ ! -e "$out" ]; then
        log_changed     "  update: dest missing"
        return 2
        
    elif [ "$APPLY_FORCE" = 1 ]; then
        log_changed     "  update: forced"
        return 2
    fi

    # check deps
    for dep in "${@:2}"; do
        # check
        if [ ! -e "$dep" ]; then
            warn        "$out: Missing source: $dep"

        elif [ "$out" -ot "$dep" ]; then
            log_changed "   changed: $dep"
            return 1
        else
            log_debug   "  check: $dep"
        fi
    done

    log_debug           "  up-to-date"
    return 0
}
