#!/bin/sh /etc/rc.common
# Copyright (C) 2010-2015 OpenWrt.org

START=99
USE_PROCD=1


LIST_SEP="
"

unregex() {
   echo "$1" | sed -e 's/[]\/()$*.^|[]/\\&/g'
}

option_word_to_digit() {
    word=$(grep -ioE "\b$2=\S+" "$1"|awk -F= '{print $2}')
    digit=$(echo "$3" |grep -oE "$word/\S+"|awk -F'/' '{print $2}')
    sed -i "s/\b$2=$word\b/$2=$digit/g" "$1"
}

encrypt_password() {
	pass_notencryted=$(grep -ioE "\b$2=[^\n]+" "$1"|sed "s/.*$2=//g")
	pass_encryted=$(echo -n $pass_notencryted|md5sum|grep -oE "[a-z0-9]{32}")
	[[ -z $pass_notencryted ]] || sed -i "s/\b$2=$(unregex $pass_notencryted)/$2=$pass_encryted/g" "$1"
}

write_dat_file() {
	if [[ -s "$1" ]] ; then
		cat "$1" > "$2"
	else
		[[ -s "$2" ]] && cat "$2" > "$1"
	fi
}

set_params() {
	cat /etc/amule/amule.conf.template > "$config_file"
	local p; local v; local s="$1"; shift
	for p in $*; do
		config_get v "$s" "$p"
		IFS="$LIST_SEP"
		for v in $v; do
			[ -n "$v" ] && (
				sed -i "s;|$(echo $p|tr '[a-z]' '[A-Z]'|sed -e 's|_||g')|;$(unregex $v);g" "$config_file"
			)
		done
		unset IFS
	done
	
	#delete unreplaced placeholders
	sed -i "s;=|[A-Z0-9]*|;=;g" "$config_file"
	
	#convert some options to digit
	option_word_to_digit "$config_file" "ProxyType" "socks5/0 socks4/1 http/2 socks4a/3"
	option_word_to_digit "$config_file" "SeeShare" "anyone/0 friends/1 nobody/2"
	
	#encrypt password
	encrypt_password "$config_file" "ECPassword"
	encrypt_password "$config_file" "Password"
	encrypt_password "$config_file" "PasswordLow"
}

section_enabled() {
	config_get_bool enabled "$1" 'enabled' 0
	[ $enabled -gt 0 ]
}

set_owner() {
	case $(echo "$1"|grep -oE "^/[^/]+") in
	"/var"|"/tmp"|"/mnt"|"root")
		cur_user=$(ls -w50 -ld "$1"|awk '{print $3}')
		cur_group=$(ls -w50 -ld "$1"|awk '{print $4}')
		[[ $cur_user == $2 ]] || ( chown -R $2 "$1" )
		[[ $cur_group == $3 ]] || ( chgrp -R $3 "$1" )
	;;
	*)
		false
	;;
	esac
}

amule() {
	local cfg="$1"
	local USE

	local runasuser
	local incoming_dir config_dir temp_dir
	local mem_percentage
	local config_overwrite nice ionice_flags
	local cmdline

	section_enabled "$section" || return 1
	
	config_get config_dir "$cfg" 'config_dir' '/var/run/amule'
	config_get runasuser "$cfg" 'runasuser' 'daemon'
	config_get incoming_dir "$cfg" 'incoming_dir' "$config_dir/Incoming"
	config_get temp_dir "$cfg" 'temp_dir' "$config_dir/Temp"
	config_get mem_percentage "$cfg" 'mem_percentage' '50'
	config_get config_overwrite "$cfg" config_overwrite 1
	config_get nice "$cfg" nice "-19"
	config_get ionice_flags "$cfg" ionice_flags ''
	group=$(id -Gn $runasuser)
	
	case $(echo "$config_dir"|grep -oE "^/[^/]+") in
	"/var"|"/tmp"|"/mnt"|"/root"|"/home")
		true
	;;
	*)
		echo "You should set config_dir to subfolders under /var, /tmp ,/mnt or /root"
		return 1
	;;
	esac
	
	which ionice > /dev/null || ionice_flags=''

	local MEM=$(sed -ne 's!^MemTotal:[[:space:]]*\([0-9]*\) kB$!\1!p' /proc/meminfo)
	if test "$MEM" -gt 1;then
		USE=$(expr $MEM \* $mem_percentage \* 10)
	fi

	config_file="$config_dir/amule.conf"
	#[ -d "$config_dir" ] || {
		mkdir -m 0755 -p "$config_dir"
		chmod g+s "$config_dir"
		chown $group:$runasuser "$config_dir"
		touch "$config_file" "$config_dir/addresses.dat" "$config_dir/shareddir.dat" \
			"$config_dir/ipfilter_static.dat"
		[ -d "$config_dir/.aMule" ] || ln -s ./ $config_dir/.aMule
		#[ -z "$runasuser" ] || set_owner "$config_dir" $runasuser $group
	#}
	
	
	touch "$config_file"
	write_dat_file /etc/amule/addresses.dat "$config_dir/addresses.dat"
	write_dat_file /etc/amule/shareddir.dat "$config_dir/shareddir.dat"
	write_dat_file /etc/amule/ipfilter_static.dat "$config_dir/ipfilter_static.dat"

	#[ "$config_overwrite" == 0 ] || {
		set_params "$cfg" $(uci show amule|awk -F'[.=]' '{print $3}'|tr '\n' ' ')
	#}
	
	HOME="$config_dir" /usr/bin/amulecmd --create-config-from="$config_file"
	
	cmdline="/usr/bin/amuled -c $config_dir"
	[ "$ionice_flags" ] && cmdline="ionice $ionice_flags $cmdline"
	procd_open_instance
	procd_set_param command $cmdline
	procd_set_param respawn retry=60
	procd_set_param user "$runasuser"
	procd_set_param nice "$nice"
	if test -z "$USE";then
		procd_set_param limits core="0 0"
	else
		procd_set_param limits core="0 0" as="$USE $USE"
		logger -t amule "Starting with $USE virt mem"
	fi

	procd_add_jail amule log
	procd_add_jail_mount_rw $config_file
	procd_add_jail_mount_rw $incoming_dir
	procd_add_jail_mount_rw $temp_dir
	procd_close_instance
}

start_service() {
	killall -9 amuleweb >/dev/null 2>&1
	config_load 'amule'
	config_foreach amule 'amule'
}

restart() {
	stop
	sleep 2
	start
}

