#! /bin/sh
# Enable zram

grep -q 'sysprof=1' /proc/cmdline && echo "sysprof enabled, skipping zram" && exit

SCFILE=/nvram/ServiceConfig.json

# ServiceConfig file may not exist until device is connected
if [ -f "$SCFILE" ]; then
    ZRAM=`awk -F '\"' '$2 == "fw.system.zram"{ print $4 }' $SCFILE`
    if [ "$ZRAM" = "" ]; then
        ZRAM=1
    fi

    if [ "$ZRAM" = "1" ]; then
        SWAPPINESS=`awk -F '\"' '$2 == "fw.system.swappiness"{ print $4 }' $SCFILE`
        DISKSIZE=`awk -F '\"' '$2 == "fw.system.zram.disksize_kb"{ print $4 }' $SCFILE`    
    fi
else
    # defaults if no file exists
    ZRAM=1
    SWAPPINESS=50
    # leaving DISKSIZE undefined will result in disksize_kb of 25% of physical memory
fi

# range checks
if [ "$SWAPPINESS" = "" ]; then
    SWAPPINESS=50
elif [ "$SWAPPINESS" -lt "0" ]; then
    SWAPPINESS=0
elif [ "$SWAPPINESS" -gt "100" ]; then
    SWAPPINESS=100
fi

MEMTOTAL=`cat /proc/meminfo  | awk '/MemTotal/{ print  $2 }'`
# clamp range to 5%-33% of physical memory
MEM_MINIMUM=$(expr $MEMTOTAL / 20)
MEM_MAXIMUM=$(expr $MEMTOTAL / 3)
if [ -z "$DISKSIZE" ]; then
  DISKSIZE=$(expr $MEMTOTAL / 4)
elif [ "$DISKSIZE" -gt "$MEM_MAXIMUM" ]; then
  DISKSIZE=$MEM_MAXIMUM
elif [ "$DISKSIZE" -lt "$MEM_MINIMUM" ]; then
  DISKSIZE=$MEM_MINIMUM
fi
DISKSIZE="${DISKSIZE}K"

if [ "$ZRAM" = "1" ]; then
    echo $DISKSIZE > /sys/block/zram0/disksize
    mkswap /dev/zram0
    swapon /dev/zram0
    echo $SWAPPINESS > /proc/sys/vm/swappiness
fi
