#!/bin/bash
#
# File: /usr/local/bin/myvideos
#
# build and shows a list of all videos on pc, build and shows a list of all
# seen videos, and search for videos in lists, and more...
#
#    Copyright (C) 2015  Ingo Kaesmann
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
# Script template: 0.3.0
#
# Exit codes:
# 0 = OK
# 1 = Error in parameters
# 2 = Error in configfile, configfile old or not found
# 3 = Library old or not found
# 11= More than one video found
# 18= Video not found
##############################################################################
# SOURCE FILES

. /usr/local/etc/main-inka-sh.conf			# config main
. $LLIBDIR/lib-inka-std.sh				# functions general
test -e ~/.inka-mediarc && . ~/.inka-mediarc		# local config
##############################################################################
# DECLARATION OF VARIABLES

# STRINGS
pkgname=inka-media					# package name
lib_inka_std_sh_needed=1.3.6				# standard lib version
conf_file_needed=1.0.0					# conf file version
#----------------------- end of variables to configure -----------------------
version=$(grep "^VERSION" $PROGREG/$pkgname.inf | cut -f 2)	# version
scriptname=$(basename $0)				# name of script
tempfile=$TEMPDIR/$scriptname.$UID.$$.tmp		# temporary file
infolog="logger -p user.info -t $scriptname --"		# log info messages
errlog="logger -p user.err -t $scriptname -- ERROR:"	# log error messages
debuglog="logger -p user.debug -t $scriptname -- DEBUG:" # log debug messages
debug=no						# debug=yes/no
verbose=""						# verbose=""/-q/-v
opt_found=no						# opt_found=yes/no
opt=""							# option
#------------------------- end of standard variables -------------------------
videodir="$Videodir"				# Video-root dir
level="$Level"					# number of level under root dir
allvidsfile="$Allvidsfile"			# all videos file
seenvidsfile="$Seenvidsfile"			# seen videos file
newvidsfile="$Newvidsfile"			# new videos file
#-----------------------------------------------------------------------------
head="\
  ___________________________________________________________________________
 /                                                                           \\
 |                              m y v i d e o s                              |
 \\___________________________________________________________________________/"

plinemain="\
 /                                                                           \\
 | Menue: Hauptmenue                                                         |
 \\___________________________________________________________________________/"

mlinemain="\
 /                                                                           \\
 | (q)uit                          (h)ilfe                                   |
 | K(o)nfiguration...                                                        |
 | (i)nfo ueber myvideos...                                                  |
 | Liste aller Videos (e)rstellen                                            |
 | Liste (N)euer Videos erstellen                                            |
 | (n)eue Videos auflisten                                                   |
 | Liste gesehener Videos um ein Video berei(c)hern                          |
 | weite(R)e Befehle...                                                      |
 \\___________________________________________________________________________/"

plineconfig="\
 /                                                                           \\
 | Menue: Konfiguration                                                      |
 \\___________________________________________________________________________/"

mlineconfig="\
 /                                                                           \\
 | (q)uit                          (h)ilfe                         Zu(r)ueck |
 | Konfiguration (a)nzeigen                                                  |
 | Konfiguration (e)ditieren                                                 |
 \\___________________________________________________________________________/"

plineinfomyvideos="\
 /                                                                           \\
 | Menue: Info ueber myvideos                                                |
 \\___________________________________________________________________________/"

mlineinfomyvideos="\
 /                                                                           \\
 | (q)uit                          (h)ilfe                         Zu(r)ueck |
 | In(f)ormationen ueber myvideos anzeigen                                   |
 | GNU General Public (l)icense Version 2 anzeigen                           |
 \\___________________________________________________________________________/"

plinemore="\
 /                                                                           \\
 | Menue: Weitere Befehle                                                    |
 \\___________________________________________________________________________/"

mlinemore="\
 /                                                                           \\
 | (q)uit                          (h)ilfe                         Zu(r)ueck |
 | Alle Videos auf(L)isten                                                   |
 | Nach Videos in Liste aller Videos (S)uchen                                |
 | (A)nzahl aller Videos anzeigen                                            |
 | Gesehene Videos auf(l)isten                                               |
 | Nach Video in Liste gesehener Videos (s)uchen                             |
 | Video aus Liste gesehener Videos entfe(R)nen                              |
 | Maximale (a)nzahl neuer Videos anzeigen                                   |
 \\___________________________________________________________________________/"

# NUMBERS
n=0							# number of videos
err=0							# exit code
##############################################################################
# FUNCTIONS

function show_help ()
{
# Show help
# Uses: cat
# Return codes: 0

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG show_help: $# $@" >&2
	#$debuglog show_help: $# $@
fi

cat <<EOT

Aufruf: $scriptname [OPTION]... [VIDEO]
Verwaltet Videos (alle, gesehene, neue).
        -e      erstellt Liste aller Videos
        -L      listet alle Videos auf
        -S      sucht nach VIDEO in Liste aller Videos
        -A      zeigt Anzahl aller Videos
        -c      fuegt VIDEO der Liste gesehener Videos hinzu
        -l      listet gesehene Videos auf
        -s      sucht nach VIDEO in der Liste gesehener Videos
        -r      entfernt VIDEO aus der Liste gesehener Videos
        -N      erstellt Liste neuer Videos
        -n      listet neue Videos auf
        -a      zeigt Anzahl neuer Videos
        -o      gibt Ausgabe in weiterverarbeitbarer Weise aus
-h, --help      Hilfe anzeigen und beenden
 --version      Versionsinformationen anzeigen und beenden
--show-config   Programmkonfiguration anzeigen und beenden
   --debug      Debug-Modus benutzen
        -q      ohne Meldungen, sofern keine Ausgabe gefordert wird
VIDEO           Name oder Namensteil bei -S, -c, -s, -r angeben
ohne Parameter  Start des interaktiven Modus

Es kann nur eines von -e bis -a benutzt werden.

EOT
return 0
}
#-----------------------------------------------------------------------------
function help_proc ()
{
# Show help in interactive program mode.
# Uses:$PAGER
# Return codes: 0 = ok

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG help_proc: $# $@" >&2
	#$debuglog help_proc: $# $@
fi

$PAGER <<EOT

                              Hilfe fuer myvideos

==============================================================================
                              Aufbau der Ansicht

Der obere Bereich zeigt den Namen des Programms an.
Der mittlere Bereich zeigt die aktuelle Position im Menue an.
Der untere Bereich zeigt die aktuell waehlbaren Befehle an.

==============================================================================
                                  Eingabe

Die  in  runden  Klammern stehenden Buchstaben muessen je nach Angabe entweder
als Klein- oder  Grossbuchstaben  eingegeben  werden.  Abschliessend  an  eine
Eingabe ist die Enter-Taste zu druecken.

Wenn  eine  zusaetzliche  Eingabe  notwendig  ist,  erfolgt  nach der Wahl des
Menuepunkts eine  entsprechende  Frage,  deren  Antwort  mit  der  Enter-Taste
bestaetigt werden muss.

==============================================================================
                                   Ausgabe

Die  Ausgabe der Befehle erfolgt entweder auf einer neuen Seite oder im in der
Systemkonfiguration eingestellten Pager.

==============================================================================
                                  Benutzung

Nach   dem   Speichern  von  Videos  im  Videoverzeichnis  sollte  zuerst  die
Alle-Videos-Liste  aktualisiert  werden.   Dann  kann  die   Neue-Videos-Liste
aktualisiert  werden.  Nach  jedem  Sehen  eines  Videos  sollte dieses in die
Gesehene-Videos-Liste eingetragen werden. Dabei wird automatisch das Video aus
der Neue-Videos-Liste entfernt.

Wenn  nach  dem  Sehen eines Videos dessen Name geaendert werden soll,  ist es
besser, das Video zuerst in die Gesehene-Videos-Liste einzutragen, dann wieder
daraus  zu  entfernen,  danach  den  Datei- und Verzeichnisnamen des Videos zu
aendern, die Alle-Videos-Liste zu erstellen und abschliessend das Video wieder
in  die  Gesehene-Videos-Liste  einzutragen.  Dies erspart eine lange dauernde
Aktualisierung der Neue-Videos-Liste.

==============================================================================
                                  Navigation

Quit
Hilfe
Konfiguration
	|-- Quit
	|-- Hilfe
	|-- Zurueck
	|-- Anzeigen der Konfiguration
	\`-- Editieren der Konfiguration

Info ueber myvideos
	|-- Quit
	|-- Hilfe
	|-- Zurueck
	|-- Anzeigen von Informationen ueber myvideos
	\`-- Anzeigen der GNU General Public License Version 2

Liste aller Videos erstellen
Liste neuer Videos erstellen
Neue Videos auflisten
Liste gesehener Videos um ein Video bereichern
Weitere Befehle
	|-- Quit
	|-- Hilfe
	|-- Zurueck
	|-- Alle Videos auflisten
	|-- Nach Videos in Liste aller Videos suchen
	|-- Anzahl aller Videos anzeigen
	|-- Gesehene Videos auflisten
	|-- Nach Video in Liste gesehener Videos suchen
	|-- Video aus Liste gesehener Videos entfernen
	\`-- Maximale Anzahl neuer Videos anzeigen

EOT
return 0
}
#-----------------------------------------------------------------------------
function show_config ()
{
# Show configuration of program
# Uses: cat, cut, grep
# Return codes: 0

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG show_config: $# $@" >&2
	#$debuglog show_config: $# $@
fi

cat <<EOT

Video-Stammverzeichnis:
$videodir

Datei aller vorhandener Videos:
$allvidsfile

Datei aller gesehener Videos:
$seenvidsfile

Datei aller neuen Videos:
$newvidsfile

EOT

return 0
}
#-----------------------------------------------------------------------------
function main_menue ()
{
# Mainmenue.
# Uses: clear, cut, echo, find, read, rm, sort
# Return codes: 0 = ok

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG main_menue: $# $@" >&2
	#$debuglog main_proc: $# $@
fi

local cmd="" i="" string=""

while :; do
	# show quasi-windows
	clear
	echo "$head"
	echo "$plinemain"
	echo "$mlinemain"

	read cmd
	case "$cmd" in
		q)	clear;rm -f $tempfile;exit 0;;
		h)	help_proc;;
		o)	config_menue;;			# show config menue
		i)	info_myvideos_menue;;		# show info menue
		e)	# create all video file
			clear
			echo "Bitte warten."
			find $videodir -type d | sort | cut -d / -f ${level}- > $allvidsfile;;
		N)	# create newvidsfile
			clear
			echo "Bitte warten."
			grep -v -f $seenvidsfile $allvidsfile > $newvidsfile;;
		n)	$PAGER $newvidsfile;;		# show all new videos
		c)	# add video to seenvidsfile
			clear
			echo "Videos zur Gesehene-Videos-Liste hinzufuegen"
			echo ""
			echo -e "Name(nsteil) des Videos: \c"
			read string
			add_seen_video $string
			echo "Weiter mit Enter-Taste."
			read string;;
		R)	more_menue;;			# more comands menue
	esac
done

return 0
}
#-----------------------------------------------------------------------------
function config_menue ()
{
# Build config menue and get there commands
# Uses: clear, echo, read
# Return codes: 0 = ok

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG config_menue: $# $@" >&2
	#$debuglog config_menue: $# $@
fi

local cmd="" i="" string=""

while :; do
	# show quasi-windows
	clear
	echo "$head"
	echo "$plineconfig"
	echo "$mlineconfig"

	read cmd
	case "$cmd" in
		q)	clear;exit 0;;
		h)	help_proc;;
		r)	return 0;;
		a)	show_config | $PAGER;;
		e)	$EDITOR ~/.inka-mediarc;. ~/.inka-mediarc;;
	esac
done
return 0
}
#-----------------------------------------------------------------------------
function info_myvideos_menue ()
{
# Shows infos about myvideos and shows the license.
# Uses: cat, clear, echo, read, rm
# Return codes: 0 = ok

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG info_myvideos_menue: $# $@" >&2
	#$debuglog info_myvideos_menue: $# $@
fi

local cmd="" i=""

while :; do
	# show quasi-windows
	clear
	echo "$head"
	echo "$plineinfomyvideos"
	echo "$mlineinfomyvideos"

	read cmd
	case "$cmd" in
		q)	clear;exit 0;;
		h)	help_proc;;
		r)	rm -f $tempfile;return 0;;
		f)					# show cpflash info
			echo "" > $tempfile
			echo "$scriptname" >> $tempfile
			echo "Version: $version" >> $tempfile
			echo "copyright (C) 2015, Ingo Kaesmann ingo@ingokaesmann.de" >> $tempfile
			echo "Dieses Programm wird unter den Bedingungen der GPL Vers. 2 veroeffentlicht." >> $tempfile
			echo "Es wird OHNE GARANTIE vertrieben." >> $tempfile
			cat $tempfile | $PAGER;;
		l)	cat /usr/local/share/doc/packages/$pkgname/GPL-2.0.txt | $PAGER;;	# show gpl
	esac
done
return 0
}
#-----------------------------------------------------------------------------
function more_menue ()
{
# Shows menue about more comands.
# Uses: cat, clear, echo, grep, read, rm
# Return codes: 0 = ok

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG more_menue: $# $@" >&2
	#$debuglog more_menue: $# $@
fi

local cmd="" i=""

while :; do
	# show quasi-windows
	clear
	echo "$head"
	echo "$plinemore"
	echo "$mlinemore"

	read cmd
	case "$cmd" in
		q)	clear;rm -f $tempfile;exit 0;;
		h)	help_proc;;
		r)	rm -f $tempfile;return 0;;
		L)	$PAGER $allvidsfile;;		# show all videos
		S)	# search for video in allvidsfile
			clear
			echo "Suche in der Alle-Videos-Liste"
			echo ""
			echo -e "Name(nsteil) des Videos: \c"
			read string
			search_new_video $string | $PAGER;;
		A)	# show number of all videos
			clear
			count_all_videos
			echo "Weiter mit Enter-Taste."
			read string;;
		R)	# remove video from seenvidsfile
			clear
			echo "Entferne Video aus Gesehene-Videos-Liste"
			echo ""
			echo -e "Name(nsteil) des Videos: \c"
			read string
			rm_seen_video $string
			echo "Weiter mit Enter-Taste."
			read string;;
		l)	$PAGER $seenvidsfile;;		# show all seen videos
		s)	# search for video in seenvidsfile
			clear
			echo "Suche in der Gesehene-Videos-Liste"
			echo ""
			echo -e "Name(nsteil) des Videos: \c"
			read string
			search_seen_video $string | $PAGER;;
		a)	# show number of new videos
			clear
			n=$(cat $newvidsfile | wc -l)
			echo "Es stehen weniger als $n neue Videos zur Verfuegung."
			echo ""
			echo "Weiter mit Enter-Taste."
			read string;;
	esac
done
return 0
}
#-----------------------------------------------------------------------------
function search_new_video ()
{
# Show all videos there have given string in name from $allvidsfile
# Par1: Name (part of name) of video
# Uses: echo, grep
# Return codes: 0 = showed, 18 = not exist

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG search_new_video: $# $@" >&2
	#$debuglog search_new_video: $# $@
fi

local p1=$1 err=0 ret=0

grep $p1 $allvidsfile				# show found videos
ret=$?
if [ $ret -gt 0  ]; then			# video not found
	echo "$p1 existiert nicht."
	err=18
fi

return $err
}
#-----------------------------------------------------------------------------
function count_all_videos ()
{
# Count all videos, or show all videos (no upper dirs) on stdout
# Par1: [--showvids]
# Uses: cat, cp, echo, rm, wc, Read_Lines, Erase_Lines
# Return codes: 0

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG count_all_videos: $# $@" >&2
	#$debuglog count_all_videos: $# $@
fi

local l=0 n=0 rest="" tfile1=$tempfile.cav.1.tmp tfile2=$tempfile.cav.2.tmp

cp $allvidsfile $tfile1				# build tempfile
Erase_Lines $tfile1 1 1 > $tfile2
cp $tfile2 $tfile1
l=$(cat $tfile1 | wc -l)			# number of lines of tempfile
while [ $n -lt $l ]; do
	let n++
	if [ -z "$opt_o" ];then
		echo -e "Bearbeite Zeile $n von $l  \r\c"
	fi
	line1=$(Read_Lines $tfile1 $n $n)	# first line
	let n++
	line2=$(Read_Lines $tfile1 $n $n)	# second line
	rest=${line2%/*}			# rm from last '/' to end of line of second line
	let n--
	if [ "$line1" == "$rest" ]; then	# first line is no video
		let l--
		Erase_Lines $tfile1 $n $n > $tfile2	# remove first line
		cp $tfile2 $tfile1
	fi
done
if [ "$1" == "--showvids" ]; then		# show all videos
	cat $tfile1
elif [ -n "$opt_o" ]; then			# show only number of all videos
	echo $n
else						# message: number of all videos
	echo "Es stehen insgesamt $n Videos zur Verfuegung."
fi

rm -f $tfile1 $tfile2
return 0
}
#-----------------------------------------------------------------------------
function add_seen_video ()
{
# Add the seen video to seenvidsfile
# Par1: Name (part of name) of video
# Uses: cp, echo, grep, rm
# Return codes: 0 = added, 1 = name wrong, 11 = more than one videos exist

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG add_seen_video: $# $@" >&2
	#$debuglog add_seen_video: $# $@
fi

local p1=$1 line="" vid="" err=0 m=0 n=0

m=$(grep -c "$p1" $allvidsfile)		# number of found videos in $allvidsfile

if [ $m -eq 0 ]; then			# no video found in $allvidsfile
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - $p1 nicht gefunden!"
	fi
	err=1
elif [ $m -eq 1 ]; then			# one video found in $allvidsfile
	line=$(grep "$p1" $allvidsfile)		# read line
	vid=${line##*/}				# video name
	n=$(grep -c "$vid" $seenvidsfile)	# number of seen videos there have given string in name
	if [ $n -eq 0 ]; then			# video not found in $seenvidsfile
		echo $vid >> $seenvidsfile		# add video to seenvidsfile
		grep -v $line $newvidsfile > $tempfile	# remove line of video from $newvidsfile
		cp $tempfile $newvidsfile
		rm $tempfile
	else					# video found in $seenvidsfile
		grep "$vid" $seenvidsfile		# show all videos there have given string in name
	fi
else					# more than one video found in $allvidsfile
	grep "$p1" $allvidsfile			# show all found videos in $allvidsfile
	err=11
fi

return $err
}
#-----------------------------------------------------------------------------
function rm_seen_video ()
{
# Remove seen video this have given string in name from $seenvidsfile
# Par1: Name (part of name) of video
# Uses: cut, cp, echo, grep, Erase_Lines
# Return codes: 0 = removed, 1 = name wrong, 11 = name not enough precise

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG rm_seen_video: $# $@" >&2
	#$debuglog rm_seen_video: $# $@
fi

local p1=$1 fline=0 eline=0 m=0 err=0

m=$(grep -c "$p1" $seenvidsfile)		# number of found seen videos

if [ $m -eq 0 ]; then				# no video found, parameter wrong
      echo "Fehler - $p1 ist falsch!"
      err=1
elif [ $m -eq 1 ]; then				# one video found
      fline=$(grep -n "$p1" $seenvidsfile | cut -d : -f 1) 	# read line number of video
      Erase_Lines $seenvidsfile $fline $fline > $tempfile	# rm line
      cp $tempfile $seenvidsfile				#   of $seenvidsfile
else						# more than one video found
      grep "$p1" $seenvidsfile				# show all found videos
      err=11
fi

rm -f $tempfile
return $err
}
#-----------------------------------------------------------------------------
function search_seen_video ()
{
# Show all seen videos there have the given string in name
# Par1: Name (part of name) of video
# Uses: echo, grep
# Return codes: 0 = showed, 18 = not seen

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG search_seen_video: $# $@" >&2
	#$debuglog search_seen_video: $# $@
fi

local p1=$1 err=0 ret=0

grep $p1 $seenvidsfile				# show found videos
ret=$?
if [ $ret -gt 0  ]; then			# video not found
	echo "$p1 noch nie gesehen."
	err=18
fi

return $err
}
#-----------------------------------------------------------------------------
function count_not_seen_videos ()
{
# Count all not seen videos, or show not seen videos on stdout
# Par1: [--showvids]
# Uses: cat, echo, grep, rm, count_all_videos
# Return codes: 0

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG count_not_seen_videos: $# $@" >&2
	#$debuglog count_not_seen_videos: $# $@
fi

local n=0 tfile1=$tempfile.cnsv.1.tmp tfile2=$tempfile.cnsv.2.tmp old_opt_o="$opt_o"

if [ -z "$opt_o" ]; then
	echo "Bitte warten."
fi
opt_o="-o"					# set $opt_o
count_all_videos --showvids > $tfile1		# build list of all videos (no upper dirs)
grep -v -f $seenvidsfile $tfile1 > $tfile2	# build list of not seen videos
opt_o="$old_opt_o"				# restore $opt_o

if [ "$1" == "--showvids" ]; then			# show not seen videos
	cat $tfile2 
else
	n=$(cat $tfile2 | wc -l)		# number of not seen videos
	if [ -n "$opt_o" ]; then			# show only number of not seen videos
		echo $n
	else						# message: number of not seen videos
		echo "Es stehen $n ungesehene Videos zur Verfuegung."
	fi
fi

rm -f $tfile1 $tfile2
return 0
}
##############################################################################
# PARSE COMMANDLINE

# Read all options with args and all additional args into variables.
# Stop parsing after last parameter.
# Try to do a check on all parameters and version numbers.
# Handle options -h, -C and -V directly.
# Exit on error.

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG Parse Commandline: $# $@" >&2
	#$debuglog Parse Commandline: $# $@
fi

# get options and options with arguments
while [ "${1:0:1}" == "-" ]; do				# get all options
	case "$1" in
	  -h|--help)	opt=-h;;			# option -h
	  --version)	opt=--v;; 			# option --version
	  --show-config) opt=--s;;			# option --show-config
	  --debug)	debug=yes;;			# option --debug
	  -q|--quiet)	verbose=-q;;			# option -q
#	  -v|--verbose)	verbose=-v;;			# option -v
#-------------------------- end of standard options --------------------------
	-e|-L|-S|-A|-c|-l|-s|-r|-N|-n|-a)	opt="$1";;	# option -e,-L,-S,-A,-c,-l,-s,-r,-N,-n,-a
	  -o)	opt_o=$1;;				# option -o
#	  -z)	opt_z=$1				# option -z + 1 arg
#		if [ "$#" -gt 1 ] & [ "${2:0:1}" != "-" ]; then	# par2 is 1.arg of opt_z
#			opt_z1=$2
#			shift		# shift option and all args - 1 arg
#		else					# error no arg
#			if [ "$verbose" != -q ]; then
#				echo "Fehler - Wert fuer Option $1 fehlt!" >&2
#			else
#				$errlog arg for option $1 is missing
#			fi
#			exit 1
#		fi;;
	  *)	if [ "$verbose" != "-q" ]; then
			echo "Fehler - Option $1 falsch!" >&2	# error
		else
			$errlog unknown option $1
		fi
		exit 1;;
	esac
	shift
	opt_found=yes
done

# handle standard options -h, --v, --s
case "$opt" in
  -h)	show_help; exit 0;;					# show help
  --v)	echo "$scriptname (${pkgname}) $version"; exit 0;;	# show version
  --s)	show_config; exit 0;;					# show config
esac

# check arguments after options
case "$opt" in
  -S|-c|-s|-r)	if [ $# -eq 1 ]; then			# parameter count ok
				arg1="$1"
				shift
		else					# error in param count
			if [ "$verbose" != "-q" ]; then
				echo "Fehler - Parameteranzahl falsch!" >&2
			else
				$errlog parameter count wrong
			fi
			exit 1
		fi;;
  *)	if [ $# -ne 0 ]; then				# error in param count
		if [ "$verbose" != "-q" ]; then
			echo "Fehler - Parameteranzahl falsch!" >&2
		else
			$errlog parameter count
		fi
		exit 1
	fi;;
esac
##############################################################################
# CHECK LIBRARY AND CONFIG
# Exit on error

# check library
Compare_Version $lib_inka_std_sh_needed $Lib_Inka_Std_Sh_Version
ret=$?						# (ret: 0,1,2,9,127)
if [ $ret -eq 1 ]; then				# needed lib-version higher than installed
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - Programm benoetigt neuere Version von lib-inka-std.sh!" >&2
	else
		$errlog newer version of lib-inka-std.sh needed
	fi
	exit 3
elif [ $ret -eq 9 ] || [ $ret -eq 127 ]; then	# other error (version or lib missing)
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - Versionspruefung von lib-inka-std.sh nicht moeglich!"
	else
		$errlog check of version of lib-inka-std.sh impossible
	fi
	exit 3
else						# check ok, reset $ret
	ret=0
fi

# check version of config files			# set config var!
#Compare_Version $conf_file_needed $Program_Conf
Compare_Version $conf_file_needed $Inka_Media_Rc
ret=$?						# (ret: 0,1,2,9)
if [ $ret -eq 1 ]; then				# needed config-version higher than installed
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - $scriptname benoetigt neuere Version der Konfig-datei!" >&2
	else
		$errlog newer version of conf file needed
	fi
	exit 2
elif [ $ret -eq 9 ]; then			# other error (version of conffile missing)
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - Versionspruefung der Konfig-datei von $scriptname nicht moeglich!"
	else
		$errlog check of version of conf file impossible
	fi
	exit 2
else						# check ok, reset $ret
	ret=0
fi
##############################################################################
# MAINPROGRAM
# Uses: cat, cp, find, grep, rm, test

if [ "$debug" == "yes" ]; then			# debug
	echo "DEBUG Main: $# $@" >&2
	#$debuglog Main: $# $@
fi

# create files, if not exist
test ! -e $allvidsfile && cp /dev/null $allvidsfile
test ! -e $newvidsfile && cp /dev/null $newvidsfile
test ! -e $seenvidsfile && cp /dev/null $seenvidsfile


# Check what to do (initial options and args are removed from cmdline)
case "$opt" in
  -e)						# build all video file
	find $videodir -type d | sort | cut -d / -f ${level}- > $allvidsfile
	err=$?;;
  -L)						# show all videos and dirs in pager or print only videos at stout
	if [ -z "$opt_o" ]; then
		$PAGER $allvidsfile
	else
		count_all_videos --showvids
	fi
	err=$?;;
  -S)						# search for video in $allvidsfile - output at stout
	search_new_video $arg1
	err=$?;;
  -A)						# show number of all videos - output at stout
	count_all_videos
	err=$?;;
  -c)						# add video to $seenvidsfile
	add_seen_video $arg1
	err=$?;;
  -r)						# remove video from $seenvidsfile
	rm_seen_video $arg1
	err=$?;;
  -l)						# show all seen videos in pager or print it at stout
	if [ -z "$opt_o" ]; then
		$PAGER $seenvidsfile
	else
		cat $seenvidsfile
	fi
	err=$?;;
  -s)						# search for video in $seenvidsfile - output at stout
	search_seen_video $arg1
	err=$?;;
  -N)						# build seenvidsfile
	grep -v -f $seenvidsfile $allvidsfile > $newvidsfile
	err=$?;;
  -n)						# show all not seen videos and dirs in pager or print only videos at stout
	if [ -z "$opt_o" ]; then
		$PAGER $newvidsfile
	else
		count_not_seen_videos --showvids
	fi
	err=$?;;
  -a)						# show number of not seen videos - output at stout
	count_not_seen_videos
	err=$?;;
  "")						# no opt given
	main_menue
	err=$?;;
esac

exit $err
