#!/bin/bash

# Copyright (c) Microsoft Corporation.
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

set -e

# Logs uploading function that contains the sequence of  collecting, merging and uploading
# the log files
cd "${BASH_SOURCE%/*}" || exit

mkdir -p ~/.mslogs

pushd ~/.mslogs > /dev/null

touch mainlogs
touch userlogs
touch brokerlogs

echo "Collecting & Merging Logs..."
echo "  1. Collecting Broker Device Logs... Requires permission to collect logs from a System Service"
sudo journalctl --system -u 'microsoft-identity-device-broker.service' --since "2 hours ago"> brokerlogs
echo "  2. Collecting Broker Logs..."
journalctl --user -u 'microsoft-identity-broker.service'  --since "2 hours ago"> userlogs


echo "  3. Merging Logs..."
cat userlogs brokerlogs | sort -k1 -k2 -k3 -k4 > mainlogs

popd > /dev/null

# Upload the logs
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

#. Create the incident
echo 'Creating Incident...'
#echo -e '\n'
response=$(powerlift --prod create-incident | jq '.')
id=$(echo "$response" | jq -r '.analysis."id"')
easyId=$(echo "$response" | jq -r '.analysis."easyId"')
analysisId=$(echo "$response" | jq -r '.analysis."analysisId"')

echo "Uploading Logs..."

#upload the logs
powerlift --prod upload-file $id  ~/.mslogs/mainlogs
powerlift --prod upload-file $id  ~/.mslogs/userlogs
powerlift --prod upload-file $id  ~/.mslogs/brokerlogs

rm ~/.mslogs/mainlogs
rm ~/.mslogs/userlogs
rm ~/.mslogs/brokerlogs

echo 'Incident Details'
echo  - INCIDENT REFERENCE: ["$easyId"]
echo  - ID: ["$id"]
echo  - ANALYSIS ID: ["$analysisId"]
echo  - INCIDENT URL ["https://powerlift.acompli.net/#/incidents/$id"]

# Use this while debugging.
# echo  - INCIDENT URL ["https://dev-powerlift-gym.acompli.net/#/incidents/$id"]