#!/bin/sh
# PCP QA Test No. 1141
# selinux install/remove testcase
#
# Copyright (c) 2017 Red Hat Inc.  All Rights Reserved.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

policy_name="pcpupstream"
policy_file="$PCP_VAR_DIR/selinux/$policy_name.pp"
which sedismod >/dev/null 2>&1 || _notrun "sedismod tool not installed (module disassembly)"
which semodule >/dev/null 2>&1 || _notrun "semodule tool not installed"
which seinfo >/dev/null 2>&1 || _notrun "seinfo tool not installed"
[ -f "$policy_file" ] || _notrun "upstream policy package not installed"
#if a matching module is already installed
#then selinux will detect the similarity and not actually install the package
$sudo semodule -l 2>&1 | grep -q "$policy_name" && exit 0
semodule_x_option=`semodule -h | grep "\-X"`

_cleanup()
{
    cd $here
    $sudo rm -rf $tmp $tmp.*
}

_semodule_remove()
{
    if [ "x$semodule_x_option" == "x" ]
    then
	echo "Removing semodule without priority option" >> $tmp.full
	$sudo semodule -r $tmp/selinux/pcpqa.pp
    else
	echo "Removing semodule with priority 1" >> $tmp.full
	$sudo semodule -X 1 -r $tmp/selinux/pcpqa.pp
    fi
}
status=1
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15

mkdir -p $tmp/selinux
cp $policy_file $tmp/selinux/pcpqa.pp

#install the module but catch any errors
if [ "x$semodule_x_option" == "x" ]
then
    echo "Installing semodule without priority option" >> $tmp.full
    error_line=`$sudo semodule -i $tmp/selinux/pcpqa.pp 2>&1 | grep ^libsepol\. | cut -f3 -d":" |cut -f3 -d" "`
    echo $error_line >> $tmp.full
else
    echo "Installing semodule with priority 1" >> $tmp.full
    # install module with priority 1
    error_line=`$sudo semodule -X 1 -i $tmp/selinux/pcpqa.pp 2>&1 | grep ^Fail | cut -f2 -d":"`
    echo $error_line >> $tmp.full
fi

if [ "x$error_line" == "x" ]
then
    _semodule_remove
    status=0
    exit
else
    if [ "x$semodule_x_option" == "x" ]
    then
	echo "Error from type: $error_line"
    else
	/usr/libexec/selinux/hll/pp 2>/dev/null $tmp/selinux/pcpqa.pp $tmp/selinux/pcpqa.cil
	echo "Error on line: $error_line from pcpqa.cil"
	awk -v error_line="$error_line" \
	    'FNR==error_line' $tmp/selinux/pcpqa.cil
    fi
    exit
fi

