#!/bin/bash
# Copyright (C) 2015-2019 Virtuozzo International GmbH
#
# This file is part of OpenVZ libraries. OpenVZ is free software; you can
# redistribute it and/or modify it under the terms of the GNU General
# Public License as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.

workdir="."
dumpdir="/vz/tmp/virtuozzo_crash_dumps"
coripper="/usr/bin/coripper"
prlctl="/usr/bin/prlctl"
prlsrvctl="/usr/bin/prlsrvctl"
systemctl="/usr/bin/systemctl"

if [ ! -x "$coripper" ]; then
  >&2 echo "Error: Unable to find coripper utility."
  exit -1
fi

if [ -n "$1" ]; then
  workdir=$1
fi

if [ ! -d "$workdir" ]; then
  >&2 echo "Error: $workdir is not a directory."
  >&2 echo "Usage: ${0} <dir>"
  exit -1
fi

if [[ ! -f "$workdir/executable" || ! -f "$workdir/pid" || ! -f "$workdir/cmdline" ]]; then
  >&2 echo "Error: $(readlink -f $workdir) is not a valid problem directory."
  >&2 echo "It doesn't contain one of the required files: "
  [ -f "$workdir/executable" ]  || >&2 echo "  executable"
  [ -f "$workdir/pid" ]         || >&2 echo "  pid"
  [ -f "$workdir/cmdline" ]     || >&2 echo "  cmdline"
  >&2 echo "Usage: ${0} <dir>"
  exit -1
fi

if ! mkdir -pm700 $dumpdir >/dev/null 2>&1; then
  >&2 echo "Error: Unable to create directory for dumps: $workdir"
  exit -1
fi

version="unknown"
release="unknown"
[[ -f "$workdir/pkg_version" ]] && version=`sed s/\\\./-/g $workdir/pkg_version`
[[ -f "$workdir/pkg_release" ]] && release=`sed -r 's/[^0-9]*([0-9]+)[^0-9]*.*/\1/' $workdir/pkg_release`

corename="$dumpdir/$(cat $workdir/executable | xargs basename).${version}-${release}.$(cat $workdir/pid).lin.lcore"

if ! touch $corename $corename.desc >/dev/null 2>&1; then
  >&2 echo "Error: Unable to create files $corename and $corename.desc"
  exit -1
fi

if ! chmod 600 $corename $corename.desc >/dev/null 2>&1; then
  >&2 echo "Warn: Unable to set the appropriate permissions to core files"
fi

$coripper "$workdir/coredump" > $corename

if ! $systemctl is-active prl-disp >/dev/null 2>&1; then
  sleep 10
fi

executable=$(cat "$workdir/executable")
if [[ $executable =~ .*/qemu-kvm.*  || $executable =~ .*/qemu-system.* ]]; then
  $prlctl problem-report "{$(sed -r 's/.*-uuid ([^ ]*) .*/\1/' "$workdir/cmdline")}" -s
else
  $prlsrvctl problem-report -s
fi

exit 0
