#!/bin/sh
# /etc/init.d/compcache: Start, stop and restart COMPCACHE daemon on SliTaz,
# at boot time or with the command line. Daemons options are configured
# with /etc/daemons.conf
#
. /etc/init.d/rc.functions
source /etc/compcache.conf

NAME="compcache"
DESC="$(_ '%s daemon' compcache)"
EXIST="$(grep -s zram0 /proc/swaps)"

case "$1" in
  start)
    if [ "$EXIST" ] ; then
      _ '%s is already running.' $NAME
      exit 1
    fi
    if [ -z "$SIZE" -o "$SIZE" = "0%" ]; then
      _ '%s disabled in %s.' $NAME '/etc/compcache.conf'
      exit 1
    fi
    action 'Loading module...'
    devices=$(awk '/cpu cores/{c=$4} /processor/{p++} /siblings/{s=$3}
	END { if (c*s>0) p/=s/c; if (p==0) p++; print p}' /proc/cpuinfo)
    modprobe zram num_devices=$devices &&
    for i in $(seq 0 $(($devices-1))); do
	awk "/MemTotal/ { printf(\"%uk\\n\", \$2 * ${SIZE%\%} / 100 / $devices) }" \
		< /proc/meminfo > /sys/block/zram$i/disksize
    done
    status

    action 'Starting %s: %s...' "$DESC" $NAME
    for i in $(seq 0 $(($devices-1))); do
	mkswap /dev/zram$i && swapon /dev/zram$i -p 100
    done
    status
    ;;
  stop)
    if [ -z "$EXIST" ] ; then
      _ '%s is not running.' $NAME
      exit 1
    fi
    action 'Stopping %s: %s...' "$DESC" $NAME
    for i in $(cd /sys/block/; ls -d zram*); do
	swapoff /dev/$i && echo 1 > /sys/block/$i/reset
    done
    status
    action 'Unloading module...'
    rmmod zram
    status
    ;;
  *)
    emsg "<n><b>$(_ 'Usage:')</b> $0 [start|stop]"
    newline
    exit 1
    ;;
esac

exit 0
