#!/bin/bash
##
#
# Vaisala software source code file
#
# Copyright (c) Vaisala Oyj 2015. All rights reserved.
#
##
set -euo pipefail

function log {
    echo "$1" >&2
}

function check_permissions {
    if [ "$EUID" != "0" ]; then
        log "You must be root to run this script."
        exit 4
    fi
}

function enable_ssh_logging {
    suffix=$(date +%Y%m%d-%H%M%S)
    conf_file=/etc/ssh/sshd_config

    set +e
    if grep -q '^LogLevel*' $conf_file; then
        set -e
        log_lvl=$(grep '^LogLevel*' $conf_file | awk '{print $2}')
        log "Log level already set to $log_lvl"
        exit 0
    fi

    if grep -q '^#LogLevel*' $conf_file; then
        sed -i".$suffix" 's/#LogLevel\ INFO/# Log level configured by vaisala-common:operating-system-hardening\nLogLevel\ INFO/' $conf_file
    else
        set -e
        echo "# Log level configured by vaisala-common:operating-system-hardening" >> $conf_file
        echo "LogLevel INFO" >> $conf_file
    fi

    log "SSH log level set to 'INFO'."
    service sshd restart
}

check_permissions
enable_ssh_logging
