#!/bin/sh

#/sys/block/zram0

#/sys/block/zram0/max_comp_streams
#/sys/block/zram0/mem_limit
#/sys/block/zram0/mem_used_max
#/sys/block/zram0/size
#/sys/block/zram0/reset

pt="/sys/block"

help()
 {
  echo "zram.sh: compressed ram block device setup program"
  echo
  echo zram.sh -h -m -pt -l -v -s -d -cl -cs -ds -ml -rs
  echo " -h   help"
  echo " -m   kernel module load"
  echo " -pt  sysfs base path if not default"
  echo " -l   list devices"
  echo " -v   view"
  echo " -s   set"
  echo " -d   set device"
  echo " -c   compression algorithm"
  echo " -ds  disksize"
  echo " -ms  max compression streams"
  echo " -ml  mem limit"
  echo " -rs  reset block device"
 }

list()
 {
  ls "${pt}" | grep "zram*"
 }

comp_alg_list()
 {
  cat "${pt}/${device}/comp_algorithm"
 }

comp_alg_set()
 {
  echo $cas > "${pt}/${device}/comp_algorithm"
 }

dsksz_view()
 {
  cat "${pt}/$device/disksize"
 }

dsksz_set()
 {
  echo $dsize > /sys/block/$device/disksize
 }

mcs_view()
 {
  cat "${pt}/$device/max_comp_streams"
 }

mcs_set()
 {
  echo ${mcs} > "${pt}/$device/max_comp_streams"
 }

ml_view()
 {
  cat "${pt}/$device/mem_limit"
 }

ml_set()
 {
  echo ${ml} > "${pt}/$device/mem_limit"
 }

rs()
 {
  echo 1 > "${pt}/$device/reset"
 }

while [ $# != 0 ]; do
 case $1 in
  -h) help
      exit;;
  -m) echo "Run command:"
      echo "modprobe zram num_devices=n"
      echo "n = number of zram block devices"
      exit;;
  -pt) shift
       pt="$1"
       shift
       continue;;
  -l) list
      exit;;
  -v) cfg_view="1"
      [ ! -z "${cfg_set}" ] && echo option -s not be set && exit 1
      shift
      continue;;
  -s) cfg_set="1"
      [ ! -z "${cfg_view}" ] && echo option -v not be set && exit 1
      shift
      continue;;
  -d) shift
      device="$1"
      [ ! -d $pt/$device ] && echo device does not exist && exit 1
      shift
      continue;;
  -c) [ -z "$device" ] && echo specify device first with -d && exit
      [ "${cfg_view}" = "1" ] && shift && comp_alg_list
      [ "${cfg_set}" = "1" ] && shift && cas="$1" && shift && comp_alg_set
      continue;;
  -ds) [ -z "$device" ] && echo specify device first with -d && exit
       [ "${cfg_view}" = "1" ] && shift && dsksz_view;
       [ "${cfg_set}" = "1" ] && shift && dsize="$1" && shift && dsksz_set
       continue;;
  -ms) [ -z "$device" ] && echo specify device first with -d && exit
       [ "${cfg_view}" = "1" ] && shift && mcs_view;
       [ "${cfg_set}" = "1" ] && shift && mcs="$1" && shift && mcs_set
       continue;;
  -ml) [ -z "$device" ] && echo specify device first with -d && exit
       [ "${cfg_view}" = "1" ] && shift && break && ml_view;
       [ "${cfg_set}" = "1" ] && shift && ml="$1" && shift && ml_set
       continue;;
  -rs) [ -z "$device" ] && echo specify device first with -d && exit
       rs
       break;;
   *) echo invalid
      exit;;
 esac
 shift
done
