#!/bin/ash
# Copyright (C) Namiki.mx
# Author:      smartinez@namiki.mx
# Description: Check the health status of the device
# Since:       Sept 2015

DIR=`dirname ${0}`
PID_FILE="/var/run/n-watchdog.pid" # pid file for this script

# if the pid file exists then finish then execution,
# this avoid to have two instances of the same process running at the same time
[ ! -s ${PID_FILE} ] || exit 0;

# saves the current pid
echo "$$" > ${PID_FILE}

# load the spacific env variables
SCHEMA="http"
HOST="develop.getin.mx"
PORT=8001
HOSTNAME=`cat /proc/sys/kernel/hostname`

WS_URL="${SCHEMA}://${HOST}:${PORT}/api/sensors/${HOSTNAME}/watchdog" # webservice URL

# requests to the webservice in order to post a status
post_event() {
    local DATA_FILE=$(get_datafile $1)
    if [ -s "${DATA_FILE}" ]; then
        post_queue $1 ${DATA_FILE}
        if [ 0 = $? ]; then
            post_single "$@"
        else
            enqueue "$@"
        fi
    else
        post_single "$@"
    fi
}

post_queue() {
    while read TIMESTAMP DISK_USAGE; do
        curl_wrapper $1 ${TIMESTAMP} ${DISK_USAGE} || return 1
        sed -i '1d' ${2} || return 1
    done < ${2}
    return 0
}

post_single() {
    if [ "" = "${2}" ]; then
        return
    fi

    curl_wrapper "$@"
    # validates the last return command exit code, if the value is <> 0 it means that something unusual happened
    # in that case we need to handle the data
    if [ ! 0 -eq $? ]; then
        enqueue "$@"
    fi
}

enqueue() {
    if [ "" = "${2}" ]; then
        return
    fi

    local DATA_FILE=$(get_datafile ${1})
    local SIZE
    local AVAILABLE

	if [ -f ${DATA_FILE} ]; then
		SIZE=$(ls -l ${DATA_FILE} | awk '{ print $5 }')
	else
		SIZE=0
	fi
	AVAILABLE=$(df $(pwd ${DATA_FILE}) | tail -n 1 | awk '{ print $4 }')

	if [ ${SIZE} -lt ${AVAILABLE} ]; then
	    echo Saving ${2} ${3} into ${DATA_FILE} ...
		echo ${2} ${3} >> ${DATA_FILE}
	fi
}

curl_wrapper() {
    DATA="{                                                                              
              \"data\": {                                                                   
                \"type\": \"sensor_status\",                                
                \"attributes\": {                                                           
                  \"event\": \"${1}\",                                                      
                  \"timestamp\": ${2},                                      
                  \"disk_usage\": \"${3}\"                                                  
                }                                                           
              }                                                                             
            }"

    echo Posting "$@" to "${WS_URL}" ...
    echo ${DATA}

    curl -s -m 1 \
         -X POST \
         -H "Content-Type: application/vnd.api+json" -H "Accept: application/vnd.api+json" \
         -d "${DATA}" \
         "${WS_URL}"
    return $?
}

get_disk_used() {
    echo $(df /tmp | tail -n 1 | awk '{ print $5 }')
}

get_datafile() {
    echo "/tmp/${1}.data"
}

# process the TERM signal
handle_stop() {
    rm "$PID_FILE"
    exit 0
}

# open a ssh tunnel between the getin server and each sensor
open_tunnel() {
    # open an SSH tunnel for maintain propuses
    HOSTNAME=`cat /proc/sys/kernel/hostname`
    echo ${HOSTNAME}
    PORT=5${HOSTNAME:5}
    echo ${PORT} 
    if [ ${PORT} -eq 5 ]; then
	PORT=50000
    fi

    while true; do
        CONTENT=$(date)
        COMMAND="echo $CONTENT >> tunnel/$HOSTNAME"

        echo "Openning the SSH tunnel ${PORT}:localhost:22 bluemark@${HOST} ..."
        ssh -T -K 10 -i ${DIR}/id_rsa_getin -o ExitOnForwardFailure=yes -y -R \
            ${PORT}:localhost:22 bluemark@${HOST} "$COMMAND; sleep 86400"
	echo "SSH Tunnel closed"
        sleep 1
    done
}

# first called function
main() {
    open_tunnel &

    SHUTDOWN_FILE=$(get_datafile "system_poweroff")

    if [ -s ${SHUTDOWN_FILE} ]; then
        echo Shutdown file found
        post_event "system_poweroff"
    fi

    echo $(date +%s) $(get_disk_used) >> ${SHUTDOWN_FILE}
    local LINE=$(cat ${SHUTDOWN_FILE} | wc -l)

    # send a POST request to the webservice
    post_event "system_start" $(date +%s) $(get_disk_used)

    while true; do
        local CONTENT="$(date +%s) $(get_disk_used)"
        sed -i "${LINE}s/.*/${CONTENT}/" ${SHUTDOWN_FILE}
        sleep 1
    done
}

# handle TERM signal which is sent when the n-sensor service is stopped
trap handle_stop TERM SIGINT

main "$@"
handle_stop
