#!/bin/bash

# Config
	# Le script quitte en cas de variables non déclarée
set -o nounset

scriptPath=$(readlink -f $0)
scriptDir=$(dirname ${scriptPath})

CFG_FILE='/proc/sys/kernel/yama/ptrace_scope'
NORMAL_USER="$USER"
EXEC='memwrite'
PTRACE_OK='0'

if [ ! -f "$CFG_FILE" ]; then # Pas de fichier de conf => On peut rien faire
	"$EXEC"
	exit 0
fi

if [ "$#" -eq 1 ] && [ "$USER" = 'root' ]; then
	PTRACE_PREVIOUS=$(cat "$CFG_FILE")
	echo "$PTRACE_OK" > "$CFG_FILE"
	su -c "$EXEC" "$1" # Lunch memwrite
	echo "$PTRACE_PREVIOUS" > "$CFG_FILE"
else
	# Verification du comportement de ptrace
	if [ ! "$(cat "$CFG_FILE")" = "$PTRACE_OK" ]; then
		gksudo --description 'Memwrite' "$scriptPath" "$USER"
	else # Comportement déjà ok
		"$EXEC"
	fi
fi

exit 0
