#!/bin/sh
#
# Copyright © 2018 Purism, SPC. <pureos-project@lists.puri.sm>
#
# 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 3 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, see <https://www.gnu.org/licenses/>.

set -eu

ETC_DIR="/etc/purism-power-optimisations"
VAR_DIR="/var/lib/purism-power-optimisations"
SHARE_DIR="/usr/share/purism-power-optimisations"
MANUFACTURER="Purism"

Only_once () {
	if [ -f "${VAR_DIR}/${1}" ]
	then
		return 1
	fi

	mkdir -p ${VAR_DIR}
	touch "${VAR_DIR}/${1}"

	return 0
}

if [ "$(id -u)" != "0" ]
then
	echo "E: Not running as root" >&2
	exit 1
fi

if ! dmidecode --string=baseboard-manufacturer 2>/dev/null | grep -qs "${MANUFACTURER}"
then
	echo "I: Did not detect baseboard-manufacturer as ${MANUFACTURER}; exiting."
	exit 0
fi

if ls ${ETC_DIR}/sysctl.d/* >/dev/null 2>&1
then
	for X in ${ETC_DIR}/sysctl.d/*
	do
		echo "I: Setting kernel parameters from ${X} ..."
		sysctl -p ${X}
	done
fi

if ls ${ETC_DIR}/module-parameters/* >/dev/null 2>&1
then
	for X in ${ETC_DIR}/module-parameters/*
	do
		echo "I: Setting module parameters from ${X} ..."
		while read KEY VALUE
		do
			TARGET="/sys/module/$(basename "${X}")/parameters/${KEY}"
			echo "echo \"${VALUE}\" > ${TARGET}"
			echo "${VALUE}" > "${TARGET}" || true
		done < "${X}"
	done
fi

if ls /sys/class/net/* >/dev/null 2>&1
then
	for X in /sys/class/net/*
	do
		DEVICE="$(basename "${X}")"

		if [ -d "${X}/wireless" ]
		then
			echo "I: Enabling power saving for ${DEVICE} network device ..."
			iw dev "${DEVICE}" set power_save on || true
		fi
	done
fi

if [ ! -d /var/cache/powertop ] && Only_once var-cache-powertop-populated
then
	echo "I: Installing powertop profile ..."
	cp -r ${SHARE_DIR}/powertop /var/cache
fi

# Disabled pending resolution of <http://tracker.pureos.net/T562>
# echo "I: Applying powertop profile ..."
# powertop --auto-tune || true
