#!/bin/bash
# Copyright (C) 2015-2017 Parallels IP Holdings GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
# 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.

BZ_URL="https://bugs.openvz.org"

if [[ -z $VZ_Login || -z $VZ_Password ]]; then
    echo "Invalid credentials!"
    exit 1
fi

if [[ -z ${DUMP_DIR} || ! -d ${DUMP_DIR} ]]; then
    echo "Can't access folder with logs!"
    exit 1
fi

tar czf /tmp/crash.logs.tgz ${DUMP_DIR}
if [[ ! -f /tmp/crash.logs.tgz ]]; then
    echo "Can't create archive with logs!"
    exit 1
fi

DESC=""
PKG=""
if [ -f ${DUMP_DIR}/component ]; then
    PKG=`cat ${DUMP_DIR}/component`
else
    echo "'component' file should be present in log - can't create a bug without it!"
    exit 1
fi

if [ -f ${DUMP_DIR}/reason ]; then
    DESC=`cat ${DUMP_DIR}/reason`
fi

response=`curl -D- -u ${VZ_Login}:${VZ_Password} -X POST --data "{\"fields\": {\"project\": {\"key\": \"OVZ\"}, \"fixVersions\": [{\"name\": \"Vz7.0-Update-next\"}], \"summary\": \"${PKG} crash\", \"description\": \"${PKG}${DESC}\", \"issuetype\": {\"name\": \"Bug\"}}}" -H "Content-Type: application/json" ${BZ_URL}/rest/api/2/issue/| grep '"key":'`
id=`echo $response | cut -f4 -d\"`
echo "Created issue $id ($response)"

curl -D- -u  ${VZ_Login}:${VZ_Password} -X POST  -H "X-Atlassian-Token: nocheck" -F "file=@/tmp/crash.logs.tgz" ${BZ_URL}/rest/api/2/issue/${id}/attachments

exit 0
