. /usr/share/misc/source_deviceinfo

[ $# -ne 1 ] && exit 1

case "$1" in
"size")
        # Size defaults to:
        # - 75% of RAM for devices with 2GB of RAM or less
        # - 50% of RAM for devices with between 2GB and 6GB of RAM
        # - 25% of RAM for devices with greater 6GB of RAM
        # This is loosely based on some data here:
        # https://gitlab.postmarketos.org/postmarketOS/pmaports/-/merge_requests/3752#note_1229631449

        _mem_size_mb="$(LC_ALL=C free -m | awk '/^Mem:/{print $2}')"

        if [ $_mem_size_mb -le 2048 ]; then
                _size_pct=75
        elif [ $_mem_size_mb -gt 6144 ]; then
                _size_pct=25
        else
                _size_pct=50
        fi

        # Allow overriding the size as a percentage of RAM using a deviceinfo var, or
        # disabling it completely
        if [ -n "$deviceinfo_zram_swap_pct" ]; then

                # 0% --> disable zram swap
                if [ "$deviceinfo_zram_swap_pct" == "0" ]; then
                        echo 0
                        exit 0
                fi

                _size_pct="$deviceinfo_zram_swap_pct"
        fi

        echo $(($_mem_size_mb * $_size_pct / 100))
        exit 0
        ;;
"algo")
        # Default to zstd compression, and allow overriding via deviceinfo
        # TODO: Ensure deviceinfo uses valid and usable algorithm
        echo "${deviceinfo_zram_swap_algo:-zstd}"
        exit 0
        ;;
*)
        exit 1
        ;;
esac
