#!/bin/sh
#  Author: Jamie Strandboge <jamie@ubuntu.com>
#  Copyright (C) 2015 Canonical Ltd.
#
#  This script is distributed under the terms and conditions of the GNU General
#  Public License, Version 3 or later. See http://www.gnu.org/copyleft/gpl.html
#  for details.

set -e

usage() {
    cat <<EOM
Usage `basename $0` list [OPTIONS]

-v POLICYVERSION      specify policy version (default: highest supported)
-V POLICYVENDOR       specify policy vendor (default: autodetect)
EOM
}

detect_policy_version() {
    if [ ! -f "/etc/lsb-release" ]; then
        echo "Could not autodetect policy version" >&2
        exit 1
    fi
    v=`grep "DISTRIB_RELEASE" /etc/lsb-release | cut -d '=' -f 2`

    if [ ! -d "/usr/share/apparmor/easyprof/templates/$policy_vendor/$v" ]; then
        v=`ls -1 /usr/share/apparmor/easyprof/templates/ubuntu | tail -1`
    fi

    echo $v
}

detect_policy_vendor() {
    if [ -x /usr/bin/snappy ]; then
        snappy info | grep '^release: ' | cut -d ' ' -f 2 | cut -d '/' -f 1
    elif [ -f "/etc/lsb-release" ]; then
        grep "DISTRIB_ID" /etc/lsb-release | cut -d '=' -f 2 | tr [A-Z] [a-z]
    else
        echo "Could not autodetect policy vendor" >&2
        exit 1
    fi
}

cmd="$1"
if [ -z "$cmd" ] || [ "$cmd" != "list" ]; then
    usage
    exit 1
fi
shift

policy_vendor=
policy_version=

while getopts "v:V:" opt
do
    case "$opt" in
        v) policy_version="$OPTARG";;
        V) policy_vendor="$OPTARG";;
        h) usage ; exit 0;;
        *) usage ; exit 1;;
    esac
done
shift $(($OPTIND - 1))

if [ -z "$policy_vendor" ]; then
    policy_vendor=`detect_policy_vendor`
fi
if [ -z "$policy_version" ]; then
    policy_version=`detect_policy_version`
fi

echo "System policy:"
echo " Policy vendor: $policy_vendor"
echo " Policy version: $policy_version"
echo " Templates: "
for t in `aa-easyprof --list-templates --policy-version=$policy_version --policy-vendor=$policy_vendor | sort` ; do
    echo "  $t"
done
echo " Policy groups: "
for g in `aa-easyprof --list-policy-groups --policy-version=$policy_version --policy-vendor=$policy_vendor | sort` ; do
    echo "  $g"
done

echo "Framework policy:"
echo " Templates: "
if [ -d /var/lib/snappy/apparmor/templates ]; then
    for t in `ls -1 /var/lib/snappy/apparmor/templates` ; do
        echo "  $t"
    done
fi
echo " Policy groups: "
if [ -d /var/lib/snappy/apparmor/policygroups ]; then
    for g in `ls -1 /var/lib/snappy/apparmor/policygroups` ; do
        echo "  $g"
    done
fi
