#!/bin/sh

awk '

func findorphaned( \
    IS_TARGET, IS_REFERENCED, CMD, line, a)
{
    print("--- FINDORPHANED STARTED [ " strftime("%T") " ] ---")
    CMD = "{ find /video? -follow ! -type d -xtype l -print0 | " \
            "xargs -0 ls --time-style=long-iso -l; } 2>&1"
    while (CMD | getline line > 0) {
        split(line, a)

	# find behavior has been changed, we must check 
	# explicitly here (compared to newer systems like etch)
	if (!match(a[1], "^lrwxrwxrwx") \
	 || !match(a[8], "\\.(vdr|logo)$") \
	 || !match(a[9], "^->$") \
	 || !match(a[10], "\\.(vdr|logo)$") \
\
	) {
	    print("ERROR: inconsistency detected, manual intervention required")
	    print("  [ " line " ]")
	    return
	}
        if (match(a[8], "^/video[1-9]")) {
            print("ERROR: symlink in /video[1-9]")
            print("  [ " a[8] " ]")
            return
        }
        IS_REFERENCED[a[10]] = a[8]
    }
    close(CMD)

    CMD = "find /video[1-9] -follow ! -type d -print0 | " \
          "xargs -0 ls --time-style=long-iso -l"
    while (CMD | getline line > 0) {
        split(line, a)
        ++IS_TARGET[a[8]]
    }
    close(CMD)

    for (i in IS_TARGET) {
        if (IS_REFERENCED[i]) {

#print "FILE: " i " is referenced by"
#print "FILE: " IS_REFERENCED[i]

        } else {
            print("ERROR: no reference for")
            print("  [ " i " ]")
#           return
        }
    }
    for (i in IS_REFERENCED) { # gives a[10]
        if (IS_TARGET[i]) {
            # OK
        } else {

	    # this is effectively void, see comment above
            print("ERROR: no target for")
            print("  [ " i " ]")
            print("  referenced by")
            print("  [ " IS_REFERENCED[i] " ]") # gives a[8]
#           return
        }
    }
    print("--- FINDORPHANED STOPPED [ " strftime("%T") " ] ---")
}

BEGIN {
    findorphaned()
}

'
