#!/bin/sh -efu

# This file is a part of ALT Linux SeLinux policy.
# Copyright (C) 2013 ALT Linux company

# This helper should be runned in trusted domain.

readonly LOWEST_LEVEL="s0"
readonly PROG="${PROG:-${0##*/}}"

readonly CFG="/etc/security/alt.newrole/dirs"

msg() {
    logger -t "$PROG" "$@"
    echo "$PROG --" "$@" >&2
}

verbose() {
    if [ -n "${VERBOSE+1}" ]; then
        msg "VERBOSE:" "$@"
    fi
}

fatal() {
    msg "$@"
    exit 1
}

[ -r "$CFG" ] || fatal "Can't get config $CFG"

readonly IAM="$(whoami)"
[ -n "$IAM" ] || fatal "Can't get my name"
verbose "User: $IAM" 

readonly MYHOME="$(getent passwd "$IAM" | cut -d ':' -f 6)"
[ -n "$MYHOME" ] || fatal "Can't get my home"
verbose "Home: $MYHOME"

readonly MLS="$(id -Z | cut -d ':' -f 4,5 | cut -d '-' -f 1)"
[ -n "$MLS" ] || fatal "Can't get my MLS"
verbose "MLS: $MLS"

readonly DIRS=( $(sed -n -e 's/#.*//' -e '/^[[:space:]]*$/d' -E -e "/@HOME@|@LEVEL@|@USER@|@UID@/ { s,@HOME@,$MYHOME,; s/@LEVEL@/$MLS/; s/@USER@/$IAM/; s/@UID@/$UID/; p }" "$CFG") )
verbose "DIRS: ${DIRS[*]}"

for i in "${DIRS[@]}"; do
    verbose "Processing: $i"
    if [ -d "$i" ]; then
        msg "Exists: $i"
        continue
    fi

    # Create parent directory with lowest MLS:
    parent="$(dirname $i)"
    verbose "Check parent dir: $parent"

    if ! [ -d "$parent" ]; then
        msg "Create parent dir: $parent"
        mkdir -p "$parent" || msg "Can't create $parent, SKIP!"
        test -d "$parent" || continue
        chcon -l "$LOWEST_LEVEL" "$parent" || msg "Can't set securiry context for $parent"
    fi

    # Directory will be created with current MLS level.
    if mkdir -p "$i"; then
      msg "Created: $i"
    else
      msg "Can't create $i"
    fi
done

# vim: ai ts=2 sw=2 et sts=2 ft=sh
# vim: autoindent tabstop=2 shiftwidth=2 expandtab softtabstop=2 filetype=sh
