#!/bin/bash
# -*- ENCODING: UTF-8 -*-

# picalimi
#
# Launch software with quotas or limits on the use of system resources (interactive version).
#
# Copyright (c) 2013-2026: Alexis Puente Montiel   < pica (a) picalibre.org >
#
# Licensed according to GNU AGPL version 3.0.
#
# It is libre/free software; you can use, redistribute and/or modify it according to the terms of GNU AGPL as published by GNU, version 3.0, 19 November 2007.
#
# It is distributed in the hope that it will be useful, but without any warranty. Read GNU AGPL version 3.0 for additional details.
#
# A copy of GNU AGPL version 3.0 is available at /usr/share/doc/<software-package-name>/agpl-3.0.txt (additionally on Internet as text at https://www.gnu.org/licenses/agpl-3.0.txt and as HTML at https://www.gnu.org/licenses/agpl-3.0-standalone.html ).
#
# Note: Additionally to the official e-mails, picalibre.org is strictly the only official site for this software project, please consider using it to download, report bugs and contribute.
#
# Depends: bash, cgroup-tools, cgroupfs-mount (>= 1.4+devuan1-pica1), coreutils, dialog | yad | yad-pica | zenity, findutils, gawk | mawk | original-awk, grep, procps, sed, trickle
# Recommends: x11-xkb-utils
# Suggests: memlockd | earlyoom | nohang | oomd


### SCRIPT VARIABLES ########################################

CNAME="picalimi"
VERSION="1.3.1"
TITLE="PicaLim"
ICON="/usr/share/icons/picalim.png"

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=picalim
TEXTDOMAINDIR=/usr/share/locale/

# Write errors to log
ERRORLOG="$HOME/.${CNAME}.log"
if [ -e "$ERRORLOG" ] ; then
	mv -f $ERRORLOG ${ERRORLOG}.ant
fi
if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi

for i in /etc/pica-global.dist /etc/pica-global.orig /etc/pica-global /etc/pica-global.local ~/.pica-global ~/pica-global ; do
	if [ -f "$i" ] ; then
	cat "$i"
	source "$i"
	source <(cat $i | sed -e "s/=\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)/=Y/g" -e "s/=\(No\|no\|n\)/=N/g" -e "s/=\"\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)\"/=Y/g" -e "s/=\"\(No\|no\|n\)\"/=N/g")
	fi
done
if [ "$DEBUG" = "Y" ] ; then
	set -xv
	DEBUG="Y"
else
	ERRORLOG="/tmp/.${CNAME}_$(id -nu).log"
	if [ -e "$ERRORLOG" ] ; then mv -f $ERRORLOG ${ERRORLOG}.ant ; fi
	if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi
fi
if [ "$DEBUG" = "" ] ; then DEBUG="N" ; fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "$ERRORLOG") 2>&1
echo "$0" "$*" >> "$ERRORLOG"
echo "$CNAME" "$VERSION" >> "$ERRORLOG"
echo $(date +%Y-%m-%d_%H:%M:%S) $"Start" >> "$ERRORLOG"
echo "env:" >> "$ERRORLOG"
env >> "$ERRORLOG"
echo "set:" >> "$ERRORLOG"
set >> "$ERRORLOG"
#else
#exec 2>>"$ERRORLOG"
fi

# Description:
BDESCRIP=$"Launch software with quotas or limits on the use of system resources (interactive version)."
LDESCRIP=$"$TITLE is a tool to launch software with quotas or limits on the use of system resources."

# Documentation:
docu_info () {
echo "$CNAME ($VERSION) - $BDESCRIP"
echo 
echo $"Usage:" $CNAME [$"OPTIONS"]
echo 
echo $"Options:"
echo -e "$ODESCRIP"
echo 
echo $"'man $CNAME' for more information."
echo 
}
ODESCRIP=" -t""\t"$"Use terminal interface.""\n"" -k""\t"$"Use 'kdialog' if possible.""\n"" -y""\t"$"Use 'yad' if possible (by default in graphical sessions).""\n"" -z""\t"$"Use 'zenity' if possible.""\n"" -x""\t"$"Show help documentation."

while getopts tkyzx OPTION ; do
	case $OPTION in
		t )   T="Y" ; G="N"      ;;
		k )   SDIALOG="kdialog"  ;;
		y )   SDIALOG="yad"      ;;
		z )   SDIALOG="zenity"   ;;
		x )   docu_info ; exit 0 ;;
	esac
done


### DIALOG ########################################

#DEFAULTDIALOGLIST="yad zenity kdialog"
DEFAULTDIALOGLIST="yad zenity"

#if [ -t 0 ] ; then
if [ "$(setxkbmap 1>/dev/null 2>&1 ; echo $? )" -ne 0 ] ; then
	G="N" ; T="Y"
fi

if [ "$G" != "N" ] ; then
	
	if   [ "$SDIALOG" = "kdialog" ] ; then
		DIALOGLIST="kdialog yad zenity"
	elif [ "$SDIALOG" = "yad" ] ; then
		DIALOGLIST="yad zenity kdialog"
	elif [ "$SDIALOG" = "zenity" ] ; then
		DIALOGLIST="zenity yad kdialog"
	else
		DIALOGLIST="$DEFAULTDIALOGLIST"
	fi
	
	if [ "$DIALOGLIST" = "" ] ; then
		if [ "$DEFAULTDIALOGLIST" != "" ] ; then
			DIALOGLIST="$DEFAULTDIALOGLIST"
		else
			DIALOGLIST="yad zenity kdialog"
		fi
	fi
	
	if [ "$(command -v $DIALOGLIST)" = "" ] ; then
		G="N" ; T="Y"
	fi

fi


if [ "$G" = "N" ] ; then

	if [ "$(command -v dialog)" = "" ] ; then
		echo $"ERROR: No supported dialog is installed. $TITLE cannot continue."
		exit 1
	else
		
		DIALOG="dialog --cr-wrap --keep-window --output-fd 1"
		#DIALOG="dialog --cr-wrap --keep-window --output-fd 1 --no-lines --no-shadow"
		if [ "$TITLE" != "" ] ; then
			WICON="--backtitle $(echo $TITLE | sed 's| |-|g')"
		fi
		WTITLE="--title"
		WTEXT=""
		H="0"
		W="0"
		LH="0"
		CALENDAR="--calendar"
		DATEFORMAT="--date-format %Y-%m-%d"
		WTIME="--timebox"
		TIMEFORMAT="--time-format %H:%M:%S"
		DSEL="--dselect"
		FSEL="--fselect"
		WRITE="--inputbox"
		PREWRITE=""
		COLUMN=""
		PRINTCOLUMN1=""
		PRINTCOLUMN2=""
		HIDECOLUMN1=""
		HIDECOLUMN2=""
		#INPUTSEPARATOR="--column-separator"
		#OUTPUTSEPARATOR="--separate-output"
		MONOLIST="--menu"
		#MONOLIST="--radiolist"
		MULTIPLELIST="--separate-output --checklist"
		PRE=""
		POST="off"
		PRES=""
		POSTS="on"

		INFO="--msgbox"
		WAIT="--infobox"

		QYN="--yesno"
		QYNC="--yesno"
		WYN="--yesno"
		WCC="--yesno"
		WYNC="--yesno"
		WM="--msgbox"
		ERROR="--msgbox"

		FORM="--form"
		FORMT=""
		FORMSELPRE=""
		FORMSELPOST=""
		#FORMCALPRE=""
		#FORMCALPOST=""
		#FORMCLPRE=""
		#FORMCLPOST=""
		PRELAB1="1 1"
		POSTLAB1="1 10 999 0"
		PRELAB2="2 1"
		POSTLAB2="2 10 999 0"
		PRELAB3="3 1"
		POSTLAB3="3 10 999 0"

		YES="--yes-label"
		NO="--no-label"
		OK="--ok-label"
		CONTINUE="--ok-label"
		CANCEL="--cancel-label"
		EXTRABUTTON="--extra-button --extra-label"
	
	fi

else

	for i in $DIALOGLIST ; do

		if [ "$(command -v $i)" != "" ] ; then
	
			if [ "$i" = "yad" ] ; then
		
				if [ "$(yad --version | tail -n 1 | cut -d ' ' -f 1 | cut -d '.' -f 1)" -lt 2 ] ; then
					DIALOG="yad --center"  # --selectable-labels (bug in Yad < 2.0) https://github.com/v1cont/yad/blob/master/NEWS
				else
					DIALOG="yad --center --selectable-labels"  # --on-top
				fi
				if [ "$ICON" != "" ] ; then
					WICON="--window-icon $ICON"
				fi
				WTITLE="--title"
				WTEXT="--text"
				H=""
				if [ "$(yad --version | tail -n 1 | grep -aE ^'7.2')" != "" ] ; then
					W="--width=640"
				else
					W="--width=640 --text-width=640 --fixed"  # https://github.com/v1cont/yad/issues/107  https://github.com/v1cont/yad/issues/140
				fi
				LH=""
				CALENDAR="--calendar"
				DATEFORMAT="--date-format %Y-%m-%d"
				WTIME="--separator=\n --columns 3 --form"
				#TIMEFORMAT="--time-format %H:%M:%S"
				DSEL="--file --directory --filename"  # Deleted *-selection alias for --file in Yad 4.0
				FSEL="--file --filename"              # Deleted *-selection alias for --file in Yad 4.0
				WRITE="--entry"
				PREWRITE="--entry-text"
				COLUMN="--column="
				PRINTCOLUMN1="--print-column=01"
				PRINTCOLUMN2="--print-column=02"
				HIDECOLUMN1="--hide-column=01"
				HIDECOLUMN2="--hide-column=02"
				#INPUTSEPARATOR="--item-separator"
				#OUTPUTSEPARATOR="--separator="
				#MONOLIST="--entry"
				MONOLIST="--separator=\n --list --search-column=1 --no-headers"
				MONOLISTH="--separator=\n --list --search-column=1"
				MULTIPLELIST="--separator= --list --checklist --search-column=2 --no-headers"
				MULTIPLELISTH="--separator= --list --checklist --search-column=2"
				PRE="FALSE"
				POST=""
				PRES="TRUE"
				POSTS=""
				# standard gtk keybindings for next and previous search are ctrl+g and ctrl+shift+g while you can redefine them in gtk-keys.css for your theme  # https://github.com/v1cont/yad/issues/127
			
				INFO="--image=/usr/share/icons/picalibre/rm/play.png --button="$"OK"
				WAIT="--image=/usr/share/icons/picalibre/rm/play.png --no-buttons"
			
				QYN="--image=/usr/share/icons/picalibre/rm/question.png --button="$"Yes"":0 --button="$"No"":1"
				QYNC="--image=/usr/share/icons/picalibre/rm/question.png --button="$"Yes"":0 --button="$"No"":1 --button="$"Cancel"":1"
				WYN="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Yes"":0 --button="$"No"":1"
				WCC="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Continue"":0 --button="$"Cancel"":1"
				WYNC="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Yes"":0 --button="$"No"":1 --button="$"Cancel"":1"
				WM="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"OK"
				ERROR="--image=/usr/share/icons/picalibre/rm/error.png --button="$"OK"
			
				FORM="--separator=\n --form"
				FORMT="--field"
				FORMSELPRE="--field"
				FORMSELPOST=":FL"
				FORMCALPRE="--field"
				FORMCALPOST=":DT"
				FORMCLPRE="--field"
				FORMCLPOST=":CB"
				PRELAB1=""
				POSTLAB1=""
				PRELAB2=""
				POSTLAB2=""
				PRELAB3=""
				POSTLAB3=""
			
				YES="--button"
				NO="--button"
				OK="--button"
				CONTINUE="--button"
				CANCEL="--button"
				EXTRABUTTON="--button"
		
			elif [ "$i" = "zenity" ] ; then
		
				DIALOG="zenity"
				if [ "$ICON" != "" ] ; then
					WICON="--window-icon $ICON"
				fi
				WTITLE="--title"
				WTEXT="--text"
				H=""
				W="--width=640"
				LH=""
				CALENDAR="--calendar"
				DATEFORMAT="--date-format %Y-%m-%d"
				WTIME="--separator : --forms"
				#TIMEFORMAT="--time-format %H:%M:%S"
				DSEL="--file-selection --directory --filename"
				FSEL="--file-selection --filename"
				WRITE="--entry"
				PREWRITE="--entry-text"
				COLUMN="--column="
				PRINTCOLUMN1="--print-column=01"
				PRINTCOLUMN2="--print-column=02"
				HIDECOLUMN1="--hide-column=01"
				HIDECOLUMN2="--hide-column=02"
				#INPUTSEPARATOR=""
				#OUTPUTSEPARATOR="--separator=\n"
				MONOLIST="--separator=\n --list --hide-header"
				MONOLISTH="--separator=\n --list"
				MULTIPLELIST="--separator=\n --list --checklist --hide-header"
				MULTIPLELISTH="--separator=\n --list --checklist"
				PRE="FALSE"
				POST=""
				PRES="TRUE"
				POSTS=""
			
				INFO="--info"
				WAIT="--info"
			
				QYN="--question"
				QYNC="--question"
				WYN="--question"
				WCC="--question"
				WYNC="--question"
				WM="--warning"
				ERROR="--error"
			
				FORM="--forms"
				FORMT="--add-entry"
				FORMSELPRE="--add-entry"
				FORMSELPOST=""
				FORMCALPRE="--add-calendar"
				FORMCALPOST=""
				if [ "$(zenity --version | cut -d '.' -f 1 )" -ge 3 ] || [ "$(zenity --version | sed 's|\.||g')" -ge 3102 ] ; then
					FORMCLPOST="--combo-values"
					FORMCLPRE="--add-combo"
				fi
				PRELAB1=""
				POSTLAB1=""
				PRELAB2=""
				POSTLAB2=""
				PRELAB3=""
				POSTLAB3=""
			
				# Zenity <3 does not support custom buttons.
				if [ "$(zenity --version | cut -d '.' -f 1 )" -ge 3 ] ; then
					YES="--ok-label"
					NO="--cancel-label"
					OK="--ok-label"
					CONTINUE="--ok-label"
					CANCEL="--cancel-label"
					#EXTRABUTTON=""
				fi
		
#			elif [ "$i" = "kdialog" ] ; then
#		
#				# CAUTION: All 'kdialog' (TDE, KDE Plasma 4, KDE Plasma 5, KDE Plasma 6,...) are included here!
#			
#				DIALOG="kdialog"
#				if [ "$ICON" != "" ] ; then
#					WICON="--icon $ICON"
#				fi
#				WTITLE="--title"
#				WTEXT=""
#				H=""
#				W=""
#				LH=""
#				# No "--calendar" in TDE-kdialog + No "--date-format" both TDE and Plasma = There is no usable version of kdialog for calendars
#				#CALENDAR="--calendar"
#				#DATEFORMAT="--date-format %Y-%m-%d"
#				#WTIME="--timebox"
#				#TIMEFORMAT="--time-format %H:%M:%S"
#				DSEL="--getexistingdirectory"
#				FSEL="--getsavefilename"
#				#FSEL="--getopenfilename"
#				WRITE="--inputbox"
#				PREWRITE=""
#				COLUMN=""
#				PRINTCOLUMN1=""
#				PRINTCOLUMN2=""
#				HIDECOLUMN1=""
#				HIDECOLUMN2=""
#				#INPUTSEPARATOR=""
#				#OUTPUTSEPARATOR="--separate-output"
#				MONOLIST="--menu"
#				#MONOLIST="--combobox"
#				#MONOLIST="--radiolist"
#				MULTIPLELIST="--separate-output --checklist"
#				PRE=""
#				POST="off"
#				PRES=""
#				POSTS="on"
#			
#				INFO="--msgbox"
#				WAIT="--msgbox"
#			
#				QYN="--yesno"
#				QYNC="--yesnocancel"
#				WYN="--warningyesno"
#				WCC="--warningcontinuecancel"
#				WYNC="--warningyesnocancel"
#				WM="--sorry"
#				ERROR="--error"
#			
#				# No "--form" in any kdialog version
#				#FORM="--form"
#				#FORMT=""
#				#FORMSELPRE=""
#				#FORMSELPOST=""
#				#FORMCALPRE=""
#				#FORMCALPOST=""
#				#FORMCLPRE=""
#				#FORMCLPOST=""
#				#PRELAB1=""
#				#POSTLAB1=""
#				#PRELAB2=""
#				#POSTLAB2=""
#				#PRELAB3=""
#				#POSTLAB3=""
#			
#				# TDE-kdialog does not support custom buttons.
#				if [ "$(kdialog --version | grep -a Qt | grep -aEo "[0-9]" | head -n 1)" -ge 4 ] || [ "$(kdialog --version | grep -aEi kdialog | grep -aEo "[0-9]" | head -n 1)" -gt 1 ] ; then
#					YES="--yes-label"
#					NO="--no-label"
#					OK="--continue-label"
#					CONTINUE="--continue-label"
#					CANCEL="--cancel-label"
#					EXTRABUTTON="--cancel-label"
#				fi
		
			else
		
				true
		
			fi
		
		if [ "$DIALOG" != "" ] ; then break ; fi
		
		fi

	done

fi

if [ "$DIALOG" = "" ] ; then
	echo $"ERROR: No supported dialog is installed. $TITLE cannot continue."
	exit 1
fi


### BASICFUN ########################################

check_exit () {

TAILERRORLOG=$(cat "$ERRORLOG" | grep -aE "[a-zA-Z0-9\=\[]" | tail -n 10 )

echo $(date +%Y-%m-%d_%H:%M:%S)

$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"Stop due to error.\n\n$TAILERRORLOG\n" $H $W

exit 1

}

# "try again or exit" dialog window
input_error () {

echo $(date +%Y-%m-%d_%H:%M:%S)

$DIALOG $WICON $WTITLE "$TITLE" $WYN   $WTEXT $"Something went wrong.\n\nDo you want to try again?" $H $W

if [ "$?" -ne 0 ] ; then
	exit 1
else
	$REFUN
fi

}


### WELCOME ########################################

if [ "$WELCOME" != "N" ] ; then

$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"Welcome to $TITLE.\n\n$TITLE is a tool to launch software with quotas or limits on the use of system resources.\n\n$TITLE is libre/free software, licensed according to 'GNU AGPL version 3.0'.\n\nIt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.\n\nMore information at www.picalibre.org\n" $H $W

if [ "$?" -ne 0 ] ; then
	exit 0
fi

fi


### SCRIPT ########################################

set_val () {
	
	VAL=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT "$VAL_TEXT" $H $W)
	
	if [ "$?" -ne 0 ] ; then
		picalimi_general ; return 1
	fi
	
	CHECK_VAL=$(echo "$VAL" | sed 's| ||g')
	
	if [ "$CHECK_VAL" = "" ] ; then
		REFUN=picalimi_general
		input_error ; return
	fi
	
	CHECK_VAL=$(echo "$VAL" | sed "s|[0-9]||g")
	
	if [ "$CHECK_VAL" != "" ] ; then
		REFUN=picalimi_general
		input_error ; return
	fi
		
}

picalimi_general () {

unset MEM CPU DL UL

# Set variables

SELVAR=$($DIALOG $WICON $WTITLE "$TITLE" $MULTIPLELIST $WTEXT $"Please select the system resources you want to set.\n" $H $W $LH $COLUMN $COLUMN $COLUMN \
$PRE "M " $"Maximum RAM memory to use" $POST \
$PRE "R " $"Maximum % of free RAM memory to use" $POST \
$PRE "C " $"Maximum % of processor to use" $POST \
$PRE "D " $"Maximum download bandwidth to use" $POST \
$PRE "U " $"Maximum upload bandwidth to use" $POST \
$PRE "X " $"Stop now" $POST \
| sed 's|(.*)||g' | sed 's| .*||g' | sed 's|^TRUE||g' )
	
	if [ "$?" -ne 0 ] || [ "$SELVAR" = "" ] ; then
		exit 0
	fi
	
	if [ "$(echo $SELVAR | grep -o X )" != "" ] ; then
		exit 0
	fi
	
	if [ "$(echo $SELVAR | grep -o M )" != "" ] ; then
		
		MEM_F=$(free -m | grep -aEi "^Mem" | awk '{print $4}')
		
		FREETEST=$(free -m | grep -aEi "^-/+|^buffers/cach")
		if [ "$FREETEST" != "" ] ; then
			MEM_A=$(free -m | grep -aEi "^-/+|^buffers/cach" | awk '{print $NF}')
		else
			MEM_A=$(free -m | grep -aEi "^Mem" | awk '{print $NF}')
		fi
		
		VAL_TEXT=$"Please write a value of maximum RAM memory as an integer in MB, for example write '500' for 500 MB, '1000' for 1000 MB = 1 GB.\n\nCurrently there are $MEM_A MB free.\n"
		# Currently there are $MEM_F MB free and a total of $MEM_A MB can be used.\n"
		
		set_val
		
		PRE_MEM=$VAL
		
	fi
	
	if [ "$(echo $SELVAR | grep -o R )" != "" ] ; then
		
		if [ "$PRE_MEM" != "" ] ; then
		
		$DIALOG $WICON $WTITLE "$TITLE" $WYN   $WTEXT $"Maximum RAM memory to use is already set.\n\nDo you want to continue (using the value already set)?" $H $W
		
		if [ "$?" -ne 0 ] ; then
			picalimi_general
			return
		fi
		
		else
		
		MEM_F=$(free -m | grep -aEi "^Mem" | awk '{print $4}')
		
		FREETEST=$(free -m | grep -aEi "^-/+|^buffers/cach")
		if [ "$FREETEST" != "" ] ; then
			MEM_A=$(free -m | grep -aEi "^-/+|^buffers/cach" | awk '{print $NF}')
		else
			MEM_A=$(free -m | grep -aEi "^Mem" | awk '{print $NF}')
		fi
		
		VAL_TEXT=$"Please write a value of maximum % of free RAM memory as an integer percentage without decimals or symbols, for example write '90' for 90%.\n\nCurrently there are $MEM_A MB free.\n"
		# Currently there are $MEM_F MB free and a total of $MEM_A MB can be used.\n"
		
		set_val
		
		PRE_MEM_R=$VAL
		PRE_MEM=$(expr $MEM_A \* $PRE_MEM_R / 100)
		
		fi
		
	fi
	
	if [ "$(echo $SELVAR | grep -o C )" != "" ] ; then
		
		VAL_TEXT=$"Please write a value of maximum % of processor as an integer percentage without decimals or symbols, for example write '90' for 90%.\n"
		
		set_val
		
		PRE_CPU=$VAL
	
	fi
	
	if [ "$(echo $SELVAR | grep -o D )" != "" ] ; then
		
		VAL_TEXT=$"Please write a value of maximum download bandwidth as an integer in kB/s, for example write '500' for 500 kB/s, '1000' for 1000 kB/s = 1 MB/s.\n"
		
		set_val
		
		PRE_DL=$VAL
	
	fi
	
	if [ "$(echo $SELVAR | grep -o U )" != "" ] ; then
		
		VAL_TEXT=$"Please write a value of maximum upload bandwidth as an integer in kB/s, for example write '500' for 500 kB/s, '1000' for 1000 kB/s = 1 MB/s.\n"
		
		set_val
		
		PRE_UL=$VAL
	
	fi

#for i in MEM CPU DL UL USER ; do
#	if [ "$(eval echo \$$i)" != "" ] ; then
#		declare ${i}_TEXT="\n\n$i=$(eval echo \$$i)\n\n"
#	else
#		declare ${i}_TEXT=""
#	fi
#done ; echo MEM_TEST=$MEM_TEXT

if [ -n "$PRE_MEM" ] ; then MEM_TEXT=$"The maximum RAM memory is set to ${PRE_MEM} MB.\n" ; fi
if [ -n "$PRE_CPU" ] ; then CPU_TEXT=$"The maximum % of processor is set to ${PRE_CPU} %.\n" ; fi
if [ -n "$PRE_DL"  ] ; then DL_TEXT=$"The maximum download bandwidth is set to ${PRE_DL} kB/s.\n" ; fi
if [ -n "$PRE_UL"  ] ; then UL_TEXT=$"The maximum upload bandwidth is set to ${PRE_UL} kB/s.\n" ; fi

if [ -z "$PRE_MEM" ] && [ -z "$PRE_CPU" ] && [ -z "$PRE_DL" ] && [ -z "$PRE_UL" ] ; then
	check_exit
fi

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"${MEM_TEXT}${CPU_TEXT}${DL_TEXT}${UL_TEXT}\nDo you want to continue?\n" $H $W

	if [ "$?" -ne 0 ] ; then
		exit 0
	fi


# Launch the application

SW=$($DIALOG $WICON $WTITLE $"Select a software application" $FSEL /usr/bin/ $H $W)

if [ "$?" -ne 0 ] || [ "$SW" = "" ] ; then
	exit 0
fi

if [ ! -e "$SW" ] ; then
	exit 1
fi

if [ ! -x "$SW" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"$SW is not executable (if it is a self-created application, you forgot to give it the 'executable' permission)." $H $W
	exit 0
fi

CSW=$(echo "$SW" | sed "s|^/usr/local/sbin/||g" | sed "s|^/usr/local/bin/||g" | sed "s|^/usr/sbin/||g" | sed "s|^/usr/bin/||g" | sed "s|^/sbin/||g" | sed "s|^/bin/||g")

COM=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Optionally you can specify additional options." $H $W $PREWRITE "$CSW")

if [ "$COM" = "" ] ; then
	COM="$CSW"
fi

NCOM=$(echo "$COM" | cut -d ' ' -f 1 | sed "s|.*/||g")

CG=$(echo "$NCOM"_$(date +%Y%m%d%H%M%S%N))

for i in $(echo $(awk '!/^#/ { if ($4 == 1) print $1 }' /proc/cgroups) $(cat /sys/fs/cgroup/unified/cgroup.controllers 2>/dev/null) | sort -u) ; do
	cgcreate -a $(whoami):$(whoami) -t $(whoami):$(whoami) -g $i:$(whoami)/$CG
done


if [ "$PRE_MEM" != "" ] ; then
	MEM=$(expr $PRE_MEM \* 1000000 )
fi
if [ "$MEM" != "" ] ; then
	if [ -d      "/sys/fs/cgroup/memory/$(whoami)/"  ] && [ ! -e "/sys/fs/cgroup/memory/$(whoami)/$CG/"  ] ; then mkdir /sys/fs/cgroup/memory/$(whoami)/$CG/ ; fi
	if [ -d      "/sys/fs/cgroup/$(whoami)/"         ] && [ ! -e "/sys/fs/cgroup/$(whoami)/$CG/"         ] ; then mkdir /sys/fs/cgroup/$(whoami)/$CG/ ; fi
	if [ -d      "/sys/fs/cgroup/unified/$(whoami)/" ] && [ ! -e "/sys/fs/cgroup/unified/$(whoami)/$CG/" ] ; then mkdir /sys/fs/cgroup/unified/$(whoami)/$CG/ ; fi
	if [ -f      "/sys/fs/cgroup/memory/$(whoami)/$CG/memory.limit_in_bytes" ] ; then
	echo "$MEM" > /sys/fs/cgroup/memory/$(whoami)/$CG/memory.limit_in_bytes ; fi
	if [ -f      "/sys/fs/cgroup/memory/$(whoami)/$CG/memory.max_usage_in_bytes" ] ; then
	echo "$MEM" > /sys/fs/cgroup/memory/$(whoami)/$CG/memory.max_usage_in_bytes ; fi
	if [ -f      "/sys/fs/cgroup/memory/$(whoami)/$CG/memory.high" ] ; then
	echo "$MEM" > /sys/fs/cgroup/memory/$(whoami)/$CG/memory.high ; fi
	if [ -f      "/sys/fs/cgroup/memory/$(whoami)/$CG/memory.max" ] ; then
	echo "$MEM" > /sys/fs/cgroup/memory/$(whoami)/$CG/memory.max ; fi
	if [ -f      "/sys/fs/cgroup/$(whoami)/$CG/memory.limit_in_bytes" ] ; then
	echo "$MEM" > /sys/fs/cgroup/$(whoami)/$CG/memory.limit_in_bytes ; fi
	if [ -f      "/sys/fs/cgroup/$(whoami)/$CG/memory.max_usage_in_bytes" ] ; then
	echo "$MEM" > /sys/fs/cgroup/$(whoami)/$CG/memory.max_usage_in_bytes ; fi
	if [ -f      "/sys/fs/cgroup/$(whoami)/$CG/memory.high" ] ; then
	echo "$MEM" > /sys/fs/cgroup/$(whoami)/$CG/memory.high ; fi
	if [ -f      "/sys/fs/cgroup/$(whoami)/$CG/memory.max" ] ; then
	echo "$MEM" > /sys/fs/cgroup/$(whoami)/$CG/memory.max ; fi
	if [ -f      "/sys/fs/cgroup/unified/$(whoami)/$CG/memory.limit_in_bytes" ] ; then
	echo "$MEM" > /sys/fs/cgroup/unified/$(whoami)/$CG/memory.limit_in_bytes ; fi
	if [ -f      "/sys/fs/cgroup/unified/$(whoami)/$CG/memory.max_usage_in_bytes" ] ; then
	echo "$MEM" > /sys/fs/cgroup/unified/$(whoami)/$CG/memory.max_usage_in_bytes ; fi
	if [ -f      "/sys/fs/cgroup/unified/$(whoami)/$CG/memory.high" ] ; then
	echo "$MEM" > /sys/fs/cgroup/unified/$(whoami)/$CG/memory.high ; fi
	if [ -f      "/sys/fs/cgroup/unified/$(whoami)/$CG/memory.max" ] ; then
	echo "$MEM" > /sys/fs/cgroup/unified/$(whoami)/$CG/memory.max ; fi
fi

if [ "$PRE_CPU" != "" ] ; then
	CPU=$(expr 100000 \* $PRE_CPU / 100)
fi
if [ "$CPU" != "" ] ; then
	if [ -d      "/sys/fs/cgroup/cpu/$(whoami)/"     ] && [ ! -e "/sys/fs/cgroup/cpu/$(whoami)/$CG/"     ] ; then mkdir /sys/fs/cgroup/cpu/$(whoami)/$CG/ ; fi
	if [ -d      "/sys/fs/cgroup/$(whoami)/"         ] && [ ! -e "/sys/fs/cgroup/$(whoami)/$CG/"         ] ; then mkdir /sys/fs/cgroup/$(whoami)/$CG/ ; fi
	if [ -d      "/sys/fs/cgroup/unified/$(whoami)/" ] && [ ! -e "/sys/fs/cgroup/unified/$(whoami)/$CG/" ] ; then mkdir /sys/fs/cgroup/unified/$(whoami)/$CG/ ; fi
	if [ -f      "/sys/fs/cgroup/cpu/$(whoami)/$CG/cpu.cfs_quota_us" ] ; then
	echo "$CPU" > /sys/fs/cgroup/cpu/$(whoami)/$CG/cpu.cfs_quota_us ; fi
	if [ -f      "/sys/fs/cgroup/cpu/$(whoami)/$CG/cpu.max" ] ; then
	echo "$CPU" > /sys/fs/cgroup/cpu/$(whoami)/$CG/cpu.max ; fi
	if [ -f      "/sys/fs/cgroup/$(whoami)/$CG/cpu.cfs_quota_us" ] ; then
	echo "$CPU" > /sys/fs/cgroup/$(whoami)/$CG/cpu.cfs_quota_us ; fi
	if [ -f      "/sys/fs/cgroup/$(whoami)/$CG/cpu.max" ] ; then
	echo "$CPU" > /sys/fs/cgroup/$(whoami)/$CG/cpu.max ; fi
	if [ -f      "/sys/fs/cgroup/unified/$(whoami)/$CG/cpu.cfs_quota_us" ] ; then
	echo "$CPU" > /sys/fs/cgroup/unified/$(whoami)/$CG/cpu.cfs_quota_us ; fi
	if [ -f      "/sys/fs/cgroup/unified/$(whoami)/$CG/cpu.max" ] ; then
	echo "$CPU" > /sys/fs/cgroup/unified/$(whoami)/$CG/cpu.max ; fi
fi

if [ "$PRE_DL" != "" ] ; then
	DL="-d $PRE_DL"
fi

if [ "$PRE_UL" != "" ] ; then
	UL="-u $PRE_UL"
fi

if [ "$DEBUG" = "Y" ] ; then
	export CGROUP_LOGLEVEL=DEBUG
fi

if [ "$DL" = "" ] && [ "$UL" = "" ] ; then
	if [ "$MEM" = "" ] && [ "$CPU" = "" ] ; then
		$COM &
	elif [ "$MEM" != "" ] && [ "$CPU" = "" ] ; then
		cgexec -g memory:$(whoami)/$CG $COM
	elif [ "$MEM" = "" ] && [ "$CPU" != "" ] ; then
		cgexec -g cpu:$(whoami)/$CG $COM
	elif [ "$MEM" != "" ] && [ "$CPU" != "" ] ; then
		cgexec -g cpu,memory:$(whoami)/$CG $COM
	else
		echo $"ERROR"
	fi
else
	if [ "$MEM" = "" ] && [ "$CPU" = "" ] ; then
		trickle $DL $UL $COM
	elif [ "$MEM" != "" ] && [ "$CPU" = "" ] ; then
		cgexec -g memory:$(whoami)/$CG trickle $DL $UL $COM
	elif [ "$MEM" = "" ] && [ "$CPU" != "" ] ; then
		cgexec -g cpu:$(whoami)/$CG trickle $DL $UL $COM
	elif [ "$MEM" != "" ] && [ "$CPU" != "" ] ; then
		cgexec -g cpu,memory:$(whoami)/$CG trickle $DL $UL $COM
	else
		echo $"ERROR"
	fi
fi

if [ "$?" -eq 0 ] ; then
	sleep 1
	rmdir $(find /sys/fs/cgroup/ -type d | grep -aE "/$(whoami)/$CG/|/$(whoami)/$CG$" | awk '{print length($1)"\t"$1}' | sort -n -r | cut -f 2)
	exit 0
else
	sleep 1
	rmdir $(find /sys/fs/cgroup/ -type d | grep -aE "/$(whoami)/$CG/|/$(whoami)/$CG$" | awk '{print length($1)"\t"$1}' | sort -n -r | cut -f 2)
	exit 1
fi

}

picalimi_general
