#!/system/bin/sh
#
# Copyright (C) 2014 Marcin Chojnacki marcinch7@gmail.com
# Copyright (C) 2014 NovaFusion http://novafusion.pl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# Functions definitions
#
function log {
    date +[%T] | tr -d "\n"
    echo " $1"
}

function vibrate {
    if [ $LOGFILE != $SCRNAME.tgz ]
    then
        echo 250 > /sys/devices/virtual/timed_output/vibrator/enable
    fi
}

function cleanup {
    log "Cleaning up..."
    cd ..
    rm -rf $TEMPDIR
}

#
# Initial setup
#
SCRNAME=novalog
TEMPDIR=/sdcard/$SCRNAME

# Check and use arguments
if [ $# -eq 1 ] && [ $1 != "-s" ] || [ $# -gt 1 ]
then
    echo "Usage: $SCRNAME [-s]"
    exit 1
fi

if [ $# -eq 1 ] && [ $1 == "-s" ]
then
    LOGFILE=$SCRNAME.tgz
else
    LOGFILE=$SCRNAME-`getprop ro.build.date.utc`-`date +%d%m%Y-%S`$((RANDOM%11+10)).tgz
fi

#
# Script entry point
#
log "NovaLog starting..."

# Check if script is not running
pidof -o $$ $SCRNAME > /dev/null
if [ $? -ne 1 ]
then
    log "Another instance is already running! Aborting..."
    exit 1
fi

# Check if screen is on
if [ `cat /sys/class/backlight/panel/brightness` -eq 0 ]
then
    log "Screen is off! Aborting..."
    exit 1
fi

vibrate

# Prepare to dump
log "Preparing working directory..."
rm -rf $TEMPDIR
mkdir $TEMPDIR

if [ $? -ne 0 ]
then
    log "Failed to prepare working directory!"
    exit 1
fi

cd $TEMPDIR

# Dump all required files
log "Dumping main log..."
logcat -f main.log -v tag -d -b main
log "Dumping system log..."
logcat -f system.log -v tag -d -b system
log "Dumping radio log..."
logcat -f radio.log -v tag -d -b radio
log "Dumping events log..."
logcat -f events.log -v tag -d -b events
log "Dumping dmesg..."
dmesg > dmesg.log
log "Dumping framebuffer..."
screencap -p screen.png

# Check if files count is correct
if [ `ls | wc -l` -ne 6 ]
then
    log "Failed to dump required files!"
    cleanup

    exit 1
fi

# Package it to tar.gz and finalize
log "Packaging..."
tar -czf $LOGFILE *
rm -f ../$LOGFILE
mv $LOGFILE ..

cleanup

log "Log generated under `pwd`/$LOGFILE"
vibrate
