#!/bin/bash
#
# usage:
#
# panorama2img <WIDTHxHEIGHT(xZOOM)> <USER> <MAP NR > <OUTPUTFILE>
#
# ex.: panorama2img 1024x576 omdadmin 1 /tmp/test.png
#

# read rc files if exist
[ -e ~/.profile ] && . ~/.profile
[ -e ~/.thruk   ] && . ~/.thruk

DIR=$(dirname "$BASH_SOURCE")

SIZE=$1
USER=$2
MAP=$3
OUTPUT=$4
#TODO req libfontconfig1

if [ "x$OUTPUT" = "x" ]; then
  echo "Usage: panorama2img <width>x<heightx<zoom> <user> <map nr> <png outputfile>"
  echo ""
  echo "ex.: panorama2img 1024x768x1.0 omdadmin 1 /tmp/test.png"
  exit 3;
fi

BASEPATH="/$OMD_SITE"
[ -z $OMD_SITE ] && BASEPATH=""
#TODO detect
PHANTOMJS="phantomjs"
EXTRAOPTIONS="--ssl-protocol=tlsv1 --web-security=no --ignore-ssl-errors=true"
SESSIONID=$(date +%s%N)
#TODO mkdir
SESSIONFILE=$OMD_ROOT/var/thruk/sessions/$SESSIONID

URL="http://localhost"$BASEPATH"/thruk/cgi-bin/panorama.cgi?map=$MAP"

WIDTH=$(echo $SIZE | awk -F x '{ print $1}')
HEIGHT=$(echo $SIZE | awk -F x '{ print $2}')
ZOOM=$(echo $SIZE | awk -F x '{ print $3}')
[ -z $ZOOM ] && ZOOM="1.0"

# create fake session
echo "none~~~127.0.0.1~~~$USER" > $SESSIONFILE

rm -f $OUTPUT

$PHANTOMJS $EXTRAOPTIONS "$DIR/panorama2img.js" "$BASEPATH" "$SESSIONID" "$WIDTH" "$HEIGHT" "$ZOOM" "$URL" "$OUTPUT" 2>&1

# ensure file is not owned by root
if [ -e "$OUTPUT" -a $UID == 0 ]; then
    [ ! -z $OMD_SITE ] && chown $OMD_SITE: $OUTPUT
fi

# remove any phantomjs dump files, since they cannot be disabled
rm -f /tmp/*.dmp
# remove fake session
rm -f $SESSIONFILE
