#!/bin/sh

if [ ! -d /ext_overlay ]; then
  echo "Enable sandbox first!"
  exit 1
fi

if [ -f /ext_overlay/swapfile ]; then
  if swapon -s | grep -q "swapfile" ; then
    echo "Swapfile already exist"
    exit 0
  fi
fi

rm -f /ext_overlay/swapfile
echo "Making /ext_overlay/swapfile "
dd if=/dev/zero of=/ext_overlay/swapfile bs=1M count=512
mkswap /ext_overlay/swapfile
chmod 0600 /ext_overlay/swapfile
swapon /ext_overlay/swapfile
echo "Create /ext_overlay/swapfile OK, setup config"

uci set fstab.@global[0].anon_swap='1'
uci set fstab.@global[0].auto_swap='1'
while uci -q delete fstab.@swap[-1]; do :; done

uci add fstab swap
uci set fstab.@swap[-1].enabled='1'
uci set fstab.@swap[-1].device='/ext_overlay/swapfile'
uci set fstab.@swap[-1].label='swapfile'
uci commit fstab

uci set system.@system[0].zram_priority=2
uci commit system

echo "Config ok, sleep 10s to reboot"
sleep 10

reboot

