#!/bin/bash
#
# ::copy::
# ::maintainer::
#
CMD=$(basename $0)
CMDVER="1.9"
CMDSTR="$CMD v$CMDVER (2023-09-30)"

set -e -u

eval $(ku-distroenv)

export DISTRIB_RELEASE DISTRIB_DESCRIPTION DISTRIB_CODENAME
export DISTRIB_FULL_ID DISTRIB_ID


usage()
{
	echo "
usage $CMD [options]

options:
  -q|--quiet	be quiet
  -D|--debug	show debug messages
  --sudo	use sudo
" >&2
	exit 127
}

cleanup()
{
	trap '' 1 2 3 ERR EXIT
	rm -f $tmp $tmp.* $out $out_index.tmp $out_wiki.tmp
	trap 1 2 3 ERR EXIT
}

dprintf()
{
	$DEBUG && {
		echo -n "D# " >&2
		printf "$@" >&2
	}
	return 0
}


add_link()
{
	local icon=$1
	local url=$2
	local desc=$3
	local ext=
	local icon_name=

	for ext in jpg png gif
	do
		 [ -f "$menu_images/$icon.$ext" ] && {
		 	icon_name="$icon.$ext"
			break
		}
	done
	if [ "$icon_name" != "" ]
	then
		# /menu-images is aliased by apache, see /etc/apache2/ku-globals.conf and
		# apache.menu-images kusa db
		dprintf "%-20s using $menu_images/$icon_name\n" "$url"
		echo "<a target=\"_blank\" href=\"$url\"><img src=\"/menu-images/$icon_name\" alt=\"$desc\"></a>"
	else
		dprintf "%-20s no icon\n" "$url"
		echo "<a target=\"_blank\" href=\"$url\">$desc</a>"
	fi
}


start_list()
{
	LIST_TITLE="$*"
	LIST=
}

add_list()
{
	LIST="$LIST  <li>$*</li>\n"
}

add_list_link()
{
	add_list $(add_link "$@")
}

close_list()
{
	[ "$LIST" == "" ] && return
	[ "X$LIST_TITLE" != "X" ] && solid_title "$LIST_TITLE"
	echo -e "<ul>\n$LIST\n</ul>" >>$out
	LIST=
	LIST_TITLE=
}





start_menu()
{
	LIST_TITLE="$*"
	LIST=
	:>$tmp.menu
}

add_menu()
{
	local icon=$1
	local url=$2
	local desc=$3
	local ext=
	local icon_name=

	for ext in jpg png gif
	do
		 [ -f $menu_images/$icon.$ext ] && {
		 	icon_name="$icon.$ext"
			break
		}
	done
	if [ "$icon_name" != "" ]
	then
		# /menu-images is aliased by apache, see /etc/apache2/ku-globals.conf and
		# apache.menu-images kusa db
		dprintf "%-20s using $menu_images/$icon_name\n" "$url"
		LIST="$LIST <a target=\"_blank\" href=\"$url\"><img src=\"/menu-images/$icon_name\" alt=\"$desc\"></a>"
	else
		dprintf "%-20s no icon\n" "$url"
		#LIST="$LIST [<a target=\"_blank\" href=\"$url\">$desc</a>]"
		echo "$url|$desc|$icon" >$tmp.menu
	fi
}

close_menu()
{
	[ "X$LIST_TITLE" != "X" ] && solid_title "$LIST_TITLE"
	echo -e "$LIST" >>$out
	echo "<p>" >>$out
	LIST=
	LIST_TITLE=
	[ -s $tmp.menu ] && add_links_from_file $tmp.menu
	rm -f $tmp.menu
	return 0
}



open_port()
{
	netstat -taun | grep -q ":$1 .*LISTEN"
}

make_header()
{

	$HasWiki || {
	 $VERBOSE && echo " no wiki, building basic frame"
	 (
	  echo '<html><head>'
	  echo ' <META TITLE="'$myname'">'
	  echo ' <style>body { font-size: 12PX; font-family: Tahoma,Verdana,Arial,Helvetica,Sans; } </style>'
	  echo '</head>'
	  echo '<body>'
	  echo '<center>'

	  # open a surrounding table
	  echo '<table border="0" width="900" bgcolor="#f0f0f0" cellpadding="5" cellspacing="5"><tr><td>'
	  echo ''

	  echo '<table border="0" bgcolor="#d0d0d0" cellpadding="2" cellspacing="2" width="100%">'
 	  echo ' <tr>'
   	  echo "  <td align=\"left\"><a target=\"_blank\" href=\"$home\"><img src=\"/customer-images/logo.png\"></a></td>"
   	  echo "  <td align=\"right\"><a target=\"_blank\" href=\"$home\"><h1><font color=\"blue\">::customer.name::</font></h1></a></td>"
 	  echo ' </tr>'
	  echo '</table>'
	  echo '<hr>'
	  echo '<p>'
	 ) >>$out
	}

	local machine_desc=

	if machine_desc=$(kusa-conf machine.desc 2>/dev/null)
	then
		:
	elif machine_desc=$(kusa-conf machine.$myname_s.desc 2>/dev/null)
	then
		:
	else
		# no machine desc, fallback
		case $class in
		  media*)	machine_desc="server multimedia" ;;
		  core*)	machine_desc="server ufficio" ;;
		  ws*)		machine_desc="linux workstation" ;;
		  laptop*)	machine_desc="linux laptop" ;;
		  server.mail*)	machine_desc="mail server" ;;
		  server.lamp*)	machine_desc="web server" ;;
		  *)		machine_desc="(no desc)" ;;
		esac
		$VERBOSE && echo " no machine desc, using fallback: $machine_desc"
	fi
	machine_desc=$(echo "$machine_desc" | sed -e "s/;/\n/g" -e "s/<br>/\n/g" | fold -s -w 20 | sed -e 's/$/<br>/g')

	(
	  echo
	  echo '<div>'
	  echo '<style type="text/css"> td {padding: 0px 15px 0px 10px;}'
	  echo '  .ku_rounded_box {'
	  echo '    border: 1px solid gray;'
	  echo '    padding: 5px;'
	  echo '    border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; -khtml-border-radius: 4px;'
	  echo '  }'
	  echo '</style>'
	  echo '<table border="0" width="100%">'

	  # +-----------------+-------+
	  # | fqdn-name               |
	  # | +-----+-------+--------
	  # | | icon | desc | | info  |
	  # | +-----+-------+ | table |
	  # +-----------------+-------+

	  echo ' <tr>'
	  echo '  <td colspan="3">'
	    solid_title '<font size="+3" color="#ffffff">'"$myname"'</font>'
	  echo '  </td>'
	  echo ' </tr>'

	  echo ' <tr>'
	  echo '  <td>'
   	  echo '   <img src="/local-images/machine-icon.png">'
	  echo '  </td>'
	  echo '  <td>'
	  echo '   <div class="ku_rounded_box">'
	  echo '    <font size="+1" color="blue"><b>'$machine_desc'</font>'
	  echo '   </div>'
	  echo '  </td>'
	  echo '  <td valign="top">'
	  echo '   <table border="0">'
	  echo '    <tr><td><b>posizione:</b></td> <td><b>::customer.location::</b></td></tr>'
	  echo '    <tr><td><b>network:</b></td> <td><b>::network.network::.0 / 24</b></td></tr>'
	  echo '    <tr><td><b>codice cliente:</b></td> <td><b>::customer.shortname:: (::customer.code::)</b></td></tr>'
  	  echo '    <tr><td><i>aggiornato al:</i></td> <td><i>'$(date "+%Y.%m.%d %H:%M")'</i></td></tr>'
	  echo '   </table>'
	  echo '  </td>'
	  echo ' </tr>'

	  echo '</table>'
	  echo '</div>'
	  echo '<hr>'
	) >>$out
}


start_table()
{
	(
	  #echo '<table cellpadding="2" style="border-spacing: 2px; background-color: white; border-collapse: separate; width: 100%;">'
	  echo '<table cellpadding="2" style="border-spacing: 2px; border-collapse: separate; width: 100%;">'
	  echo '<tbody>'
	  echo ' <tr>'
	) >>$out
}
end_table()
{
	(
	  echo ' </tr>'
	  echo '<tbody>'
	  echo '</table>'
	) >>$out
}

start_tr()	{ echo ' <tr>' >>$out; }
end_tr()	{ echo ' </tr>' >>$out; }

start_td()	{ echo '   <td bgcolor="#eee" valign="top" width="50%">' >>$out; }
end_td()	{ echo '   </td>' >>$out; }

heading2()
{
	if $HasWiki
	then
		echo "---++ $*" >>$out
	else
		echo "<h2>$*</h2>" >>$out
	fi
}

solid_title()
{
	(
  		echo '<div>'
  		echo '<style type="text/css"> td {padding: 3px 3px 3px 3px;} </style>'
  		echo '<table border="0" bgcolor="#909090" width="100%">'
  		echo ' <tr> <td valign="top">'"$*"'</td> </tr>'
  		echo '</table>'
  		echo '</div>'
		echo '<hr>'
	) >>$out
}

make_footer()
{
	echo "
<p>
<table border=\"0\" bgcolor=\"#d0d0d0\" cellpadding=\"1\" cellspacing=\"2\" width=\"100%\">
 <tr><td>
	<center>
 	<font size=\"-1\" color=\"#404040\">
	<a href=\"$maint_www\"><img src=\"/maintainer-images/logo-mini.png\" valign=\"middle\"></a>&nbsp;
	maintained by <a href=\"$maint_www\">$maint_name</a></br>
	$updated_on<br>
	page built by $CMDSTR
 	</font>
 </td></tr>
</table>" >>$out

	$HasWiki || {
		# closing surrounding table
		echo '</td></tr></table>' >>$out
	}
}



add_links_from_file()
{
	local title=
	local link=
	local url=
	local desc=
	local icon=

	exec 9<&0 <"$1"

	while read link
	do
		case $link in
		  \#*|\;*)	continue ;;
		  "")		continue ;;
		  title=*)
			[ "X$title" != "X" ] && close_list
		 	title=${link/title=/}
			start_list "$title"
			continue
			;;
		  *)
			url=$(echo "$link" | cut -d'|' -f1)
			desc=$(echo "$link" | cut -d'|' -f2)
			icon=$(echo "$link" | cut -d'|' -f3)
			desc=${desc:-$url}
			icon=${icon:-$(echo "$desc" | sed -e 's#.*/##' -e 's/\..*//')}
			add_list_link "$icon" "$url" "${desc:-$url}"
			;;
		esac
	done

	close_list
	exec 0<&9 9<&-
	return 0
}




add_menu_from_file()
{
	local title=
	local link=
	local url=
	local desc=
	local icon=

	exec 9<&0 <"$1"
	while read link
	do
		case $link in
		 \#*|\;*)	continue ;;
		 "")		continue ;;
		 title=*)
			[ "X$title" != "X" ] && close_menu
		 	title=${link/title=/}
			start_menu "$title"
			continue
			;;
		 *)
			url=$(echo "$link" | cut -d'|' -f1)
			desc=$(echo "$link" | cut -d'|' -f2)
			icon=$(echo "$link" | cut -d'|' -f3)
			desc=${desc:-$url}
			icon=${icon:-$(echo "$desc" | sed -e 's#.*/##' -e 's/\..*//')}
			[ "X$menu" = "X" ] && start_menu "::"
			add_menu "$icon" "$url" "${desc:-$url}"
			;;
		esac
	done
	exec 0<&9 9<&-
	close_menu
	return 0
}


apache_have()
{
	local dir=
	local conf=$1.conf

	for dir in /etc/apache2/conf.d /etc/apache2/conf-enabled
	do
		[ -f $dir/$conf ] && return 0
	done
	return 1
}

# (MAIN)

VERBOSE=true
DEBUG=${DEBUG:-false}
Vflag="--verbose"
SUDO=
Sflag=

while [ $# != 0 ]
do
  case $1 in
    -v|--verbose)	VERBOSE=true ; Vflag="--verbose" ;;
    -q|--quiet)		VERBOSE=false ; Vflag="--quiet" ;;
    -D|--debug)		DEBUG=true ;;
    --sudo)		SUDO="sudo"; Sflag="--sudo" ;;
    --)		break ;;
    -*|"")	usage ;;
    *)		usage ;;
  esac
  shift
done

tmp=
out_index=
out_wiki=
out=

trap "echo '*INTR*'; cleanup; exit 255" 1 2 3
trap 'echo "unkwnown error $? at $LINENO"; cleanup' ERR
trap "cleanup" EXIT


wwwdir=$(kusa-conf path.wwwdir)
docdir=$(kusa-conf www.docs)
cgidir="$docdir/../cgi-bin"
apacheuser=$(kusa-conf apache.user)
apachegroup=$(kusa-conf apache.group)
menu_images=$(kusa-conf apache.menu-images)
home=$(kusa-conf service.www)

myname=$(uname -n)
myname_s=$(uname -n | sed -e 's/\..*//')
tmp=$(mktemp /tmp/$CMD-XXXXXXX)

out_index="$docdir/index.html"
out_wiki="NONE"
out=

class=$(kusa-conf class)
model=$(kusa-conf model)
maint_www=$(kusa-conf maint_www 2>/dev/null) || :
maint_name=$(kusa-conf maint_name 2>/dev/null) || :
updated_on=$(grep 'updated on' /etc/motd 2>/dev/null) || :
kernel=$(uname -r)
arch=$(uname -m)


if [ -d $docdir/wiki ]
then
	HasWiki=true
	pubdir=$(kusa-conf wiki.pubdir)
	public_web=$(kusa-conf wiki.public_web)
	out_wiki="$pubdir/auto/mainpage.wiki"
	out="$out_wiki.tmp"
	$VERBOSE && echo " building wiki file $out_wiki"
	$SUDO jtmkpath $Vflag "$pubdir/auto"
else
	HasWiki=false
	out="$out_index.tmp"
	$VERBOSE && echo " building index file $out_index"
fi

:> $out
make_header

start_table
start_tr

# ------------------------------------

start_td		# RIGHT COLUMN

start_menu "Main Menu"
$HasWiki			&& add_menu wiki "/wiki/bin/view/::customer.wikiname::" "LA TUA DOCUMENTAZIONE (Wiki)" || :
apache_have ku-linfo		&& add_menu linfo "/linfo" "Informazioni sul sistema"
apache_have ku-roundcubemail	&& add_menu webmail "/mail" "Web Mail"
open_port 8069			&& add_menu openerp "http://$myname:8069" "Procedura Gestionale (<nop>OpenERP)" || :
open_port 9000			&& add_menu logimedia "http://$myname:9000" "Logitech Media Server" || :
open_port 32400			&& add_menu plex "http://$myname:32400/manage" "Plex Media Server" || :

open_port 10000			&& add_menu webmin "https://$myname:10000" "Sistema (webmin)"
open_port 9898			&& add_menu webmin "https://$myname:9898" "Sistema (webmin)"
open_port 631			&& add_menu cups "https://$myname:631" "Stampanti (CUPS)"
[ -f $cgidir/netdiscover ]	&& add_menu netdiscover "/cgi-bin/netdiscover" "Informazioni sulla rete"

apache_have ku-glpi		&& add_menu glpi "/glpi" "Inventario (GLPI)"
apache_have ku-ocsng-manage	&& add_menu ocsng "/ocsreports" "Inventario (OCS-NG)"
apache_have ku-phpmyadmin	&& add_menu myadmin "/mysql" "DB <nop>MySQL"
apache_have ku-phppgadmin	&& add_menu pgadmin "/pgsql" "DB <nop>PostgresSQL"
apache_have ku-phpldapadmin	&& add_menu ldapadmin "/ldap" "DB LDAP"
[ -f $cgidir/backup-status ]	&& add_menu backupstatus "/cgi-bin/backup-status" "Backup Status"
[ -f $docdir/apc-status.php ]	&& add_menu apcstatus "/apc-status.php" "Stato PHP-APC"

add_menu sysdocs "/sysdoc" "Sys Docs"

close_menu

file=$docdir/menu.left
[ -s $file ] && add_menu_from_file $file

# add common links (from kusa db)
#
kusa-conf www.link.common 2>/dev/null >$tmp || :
[ -s $tmp ] && add_links_from_file $tmp

# add machine links (from kusa db)
kusa-conf www.link.$myname 2>/dev/null >$tmp || :
kusa-conf www.link.$myname_s 2>/dev/null >>$tmp || :
[ -s $tmp ] && add_links_from_file $tmp

# add custom left links
file=$docdir/links.left
[ -s $file ] && add_links_from_file $file

end_td

# ------------------------------------

start_td		# LEFT COLUMN

# add custom right menu
file=$docdir/menu.right
[ -s $file ] && add_menu_from_file $file

# add custom right links
file=$docdir/links.right
[ -s $file ] && add_links_from_file $file

end_td

end_tr
end_table

#------------------------------



(
  echo
  echo '<hr>'
  echo '<div>'
  echo '<style type="text/css"> td {padding: 0px 15px 0px 10px;} </style>'
  echo '<table border="0" bgcolor="#d0d0d0" width="100%">'
  echo ' <tr> <td valign="top">class:</td> <td>'$class'</td></tr>'
  echo ' <tr> <td>model:</td>		   <td>'$model'</td></tr>'
  echo ' <tr> <td>release:</td>		   <td>::env.DISTRIB_DESCRIPTION:: (::env.DISTRIB_CODENAME::)</td> </tr>'
  echo ' <tr> <td>kernel:</td>		   <td>'$kernel' ('$arch')</td> </tr>'
  echo '</table>'
  echo '</div>'
  echo
) >>$out

make_footer

if [ -d $docdir/wiki ]
then
	cd $(dirname $out_wiki)
	TOOLKIT=kusa jtinstall $Vflag --parse $Sflag --user $apacheuser --group $apachegroup \
		$out $(basename $out_wiki) $apacheuser:$apachegroup
	$VERBOSE && echo " redirecting $out_index"
	(
	  echo '<html><head>'
	  echo '  <META HTTP-EQUIV="refresh" CONTENT="1; url=/wiki">'
	  echo '</head></html>'
	) >$out_index.tmp
	cd $(dirname $out_index)
	TOOLKIT=kusa jtinstall $Vflag $Sflag --user $apacheuser --group $apachegroup \
		$out_index.tmp $(basename $out_index) $apacheuser:$apachegroup 660
else
	echo "
</body>
</html>
" >>$out
	sed -e 's/<nop>//' $out | sponge $out
	cd $(dirname $out_index)
	TOOLKIT=kusa jtinstall $Vflag $Sflag --parse --user $apacheuser --group $apachegroup \
		$out $(basename $out_index) $apacheuser:$apachegroup 660
fi


exit 0
