#!/bin/bash -e
#
# Enables coredumps and adjusts storage path to work with coredumpctl. This
# takes effect immediately without requiring a reboot, persists across reboots,
# and no crash metrics are collected once this is enabled. Coredumps can be
# found in /var/lib/systemd/coredump/.
#
# Copyright (C) 2017 Endless Mobile, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

SYSCONFDIR=/etc

if [ $# -gt 0 ]; then
    if [ $1 = "-h" ] || [ $1 = "--help" ]; then
        echo "Usage:"
        echo "   `basename $0` [sysconfdir]"
        echo "Where:"
        echo "   sysconfdir = path to the system configuration (default: /etc)"
        exit 0
    fi

    SYSCONFDIR="${1}"
fi

CONF_FILENAME="99-coredump.conf"
SYSCTL_CONF_FILE="${SYSCONFDIR}/sysctl.d/${CONF_FILENAME}"
LIMITS_CONF_FILE="${SYSCONFDIR}/security/limits.d/${CONF_FILENAME}"
SYSTEM_CONF_FILE="${SYSCONFDIR}/systemd/system.conf.d/${CONF_FILENAME}"

SYSTEMD_FILENAME="50-coredump.conf"
SYSTEMD_SYSCTL_CONF_FILE="/usr/lib/sysctl.d/${SYSTEMD_FILENAME}"

# Enable coredumps
mkdir -p $(dirname "${LIMITS_CONF_FILE}")
cat <<EOF > "${LIMITS_CONF_FILE}"
# Enable coredumps for regular root (max 256MB) users and root (unlimited)
*        soft        core        unlimited
root     hard        core        256000
EOF

# Enable systemd coredumps storage
mkdir -p $(dirname "${SYSCTL_CONF_FILE}")
echo "Enabling systemd coredumps processing and storage"
ln -sf "${SYSTEMD_SYSCTL_CONF_FILE}" "${SYSCTL_CONF_FILE}"
sysctl -p "${SYSCTL_CONF_FILE}"

# Remove coredump size limits for all systemd-controlled processes by default.
# Note that this won’t override explicit LimitCORE= values in individual unit files.
mkdir -p $(dirname "${SYSTEM_CONF_FILE}")
echo "Removing coredump size limits for systemd units"
cat <<EOF > "${SYSTEM_CONF_FILE}"
[Manager]
# Do not limit coredumps by default
DefaultLimitCORE=infinity
EOF
