#!/bin/sh
usage='mkappcore appid version [key]'

# Constants.
min_interval=300     # Min seconds between cores for one app.
max_cores=2          # Max cores that can be waiting for upload.
root=/tmp/appcores   # Directory holding pending cores.

debug() {
    echo "mkappcore: $*"
}

# Get arguments.
if [ $# -lt 2 -o $# -gt 3 ]; then echo "usage: $usage"; exit 2; fi
ID="$1"
VERSION="$2"
KEY="$3"
now=$(date +%s)

# Don't generate core if this app has generated a core recently.
if [ -r $root/$ID.last ]; then
    ok_time=$(($(cat $root/$ID.last) + $min_interval))
    if [ $now -lt $ok_time ]; then debug "ERROR: core too soon ($now < $ok_time)"; exit 1; fi
fi

# Don't generate core if too many cores are already waiting for upload.
num_cores=$(ls $root/*.core 2>/dev/null | wc -l | sed 's/ //g')
if [ $num_cores -ge $max_cores ]; then debug "ERROR: too many cores ($num_cores)"; exit 1; fi

# Prepare temp directory.
TS=$(date +%Y%m%d%H%M%S)
NAME="$ID.$TS.$VERSION.core"
tmpdir=$root/$NAME.tmp
files=$tmpdir/files
rm -rf $tmpdir
mkdir -p $files
mkdir -p $files/crash
mkdir -p $files/conf

# Get the core. Ignore if it's empty.
cat /dev/ltcore > $files/crash/core
if [ ! -s $files/crash/core ]; then debug "ERROR: empty core"; rm -rf $tmpdir; fi

grep -E -f /etc/system.conf.whitelist /nvram/system.conf > $files/conf/system.conf
cp /nvram/ServiceConfig.json $files/conf/ServiceConfig.json
mv /tmp/kdmesg $files/crash/msgs

# Package the core.
tar -C $files -cf $tmpdir/tar .
if [ ! -z "$KEY" ]; then enc_arg="-k$KEY"; fi
gzip < $tmpdir/tar | enc $enc_arg 1 > $tmpdir/out

# Clean up.
mv -f $tmpdir/out $root/$NAME # atomic rename
rm -rf $tmpdir
echo -n $now >$root/$ID.last
##debug "OK: $root/$NAME ready"
