#!/bin/sh

# Copyright (c) 2016, Resilio
# All rights reserved.

HOME="/Users/$USER"
RSLSYNC_PATH="/Applications/Resilio Sync.app/Contents/MacOS/Resilio Sync"
RSLSYNC_PID_FILE="$HOME/Library/Application Support/Resilio Sync/sync.pid"
CORE_DIR="/cores"
TARGET_DUMP="$HOME/Documents/RslSync_CoreDump.omach.gz"

# Run rslsync and wait for crash

echo "Set coredump size limit"

grep "limit core unlimited" $HOME/.lauchd.conf > /dev/null 2>&1
if [ $? ]; then
	echo "limit core unlimited" >> $HOME/.launchd.conf 
fi

ulimit -c unlimited
echo "Running Resilio Sync"
"$RSLSYNC_PATH"
echo "Resilio Sync terminated"
if [ ! -f "$RSLSYNC_PID_FILE" ]; then
	echo "Can't determine Resilio Sync process ID. File '$RSLSYNC_PID_FILE' doesn't exits"	
	exit 1
fi

PID=$(cat "$RSLSYNC_PID_FILE")
echo "Compresing coredump"
COREDUMP_PATH="$CORE_DIR/core.$PID"

if [ ! -f "$COREDUMP_PATH" ]; then
	echo "Can't find coredump at '$COREDUMP_PATH'"
	exit 2
fi

cat "$COREDUMP_PATH" | gzip -c -9 > $TARGET_DUMP
echo "Coredump placed to $TARGET_DUMP, send please this file to Resilio Sync Support team via http://syncapp.zendesk.com. Thanks."
