#!/bin/bash

msg() {
    echo "$*" >&2
}

is_done() {
    grep "^$1$" /tmp/.la-fix.done > /dev/null
    return $?
}

mark_todo() {
    local f=
    for f in "$@"; do
        is_done "$f" || echo "$f" >&4
    done
}

mark_done() {
    local f=
    for f in "$@"; do
        echo "$f" >&3
    done
}

fixdeps() {
    local f="$1"
    shift
    echo "e $f"
    echo "/dependency_libs=/"
    local l= lq= ll=
    for l in "$@"; do
        lq="$(sed 's|/|\\/|g' <<< $l)"
        ll="$(sed -n 's/\.la$//;s|^.*/lib||p' <<< $l)"
        if [ -n "$ll" ]; then
            echo "s/\\('\\| \\)$lq\\( \\|'\\)/\\1-l$ll\\2/"
        else
            echo "# $l ignored"
            msg "$f: $l will not be fixed"
        fi
    done
    echo "w"
}

scan_lib() {
    #msg "$_f ..."
    local dependency_libs= _dep=
    eval `grep 'dependency_libs=' "$1" | head -1`
    local broken=()
    for dep in $dependency_libs; do
        #msg "$_dep"
        case "$dep" in
        -l*) ;;
        /*.la)
            if [ -r "$dep" ]; then
                mark_todo "$dep"
            else
                broken+="$dep"
            fi
            ;;
        esac
    done
    if [ -n "$broken" ]; then
        msg "$1: $broken"
        fixdeps "$1" $broken
    fi
    mark_done "$1"
}

scan_libdir() {
    [ -d "$1" ] || return 0
    local f=
    for f in "$1"/*.la; do
        is_done "$f" && continue
        scan_lib "$f"
    done
}

scan_todo() {
    local f=
    while read f <&5; do
        is_done "$f" && continue
        scan_lib "$f"
    done
}


exec 3> /tmp/.la-fix.done
exec 4> /tmp/.la-fix.todo
exec 5< /tmp/.la-fix.todo


if [ -z "$*" ]; then
    scan_libdir /usr/lib64
else
    local n=
    for n in "$@"; do
        if [ -d "$n" ]; then
            scan_libdir "$d"
        elif [ -r "$n" ]; then
            case "$n" in
            /*.la)
                is_done "$n" || scan_lib "$d"
                ;;
            *.la)
                msg "$n: relative path - ignored"
                ;;
            *)
                msg "$n: unknown libdir/la-file"
                ;;
            esac
        else
            msg "$n: non-existant object"
        fi
    done
fi

scan_todo
