#!/bin/bash

# Copyright (c) 2019 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

# Generate /var/shmem/stashes mount point unit file dynamically. We do that because
# we need to perform dynamic calculations to find the optimal ram size.

if [ $# -ne 3 ]; then
   echo "Expected 3 arguments: normal-dir early-dir late-dir"
   exit 1
fi

normal_dir=$1
early_dir=$2
late_dir=$3

# Obtain the total memory in the system
totalMem=$( awk '/MemTotal/ {print $2}' /proc/meminfo )

# limit1 is the totalMem minus 2G. This ensures a guaranteed 2G space in the
# memory for rest of the system to use.
# limit2 is 75% of totalMem
limit1=$( echo $totalMem | awk '{print $1 - 2097152}' )
limit2=$( echo $totalMem | awk '{print $1 * 0.75}' )

# Obtain the min of limit1 and limit2 and use that to fix the stashes partition size
# Note: The size is only a ceiling and memory is not reserved in advance.
min=$( printf "$limit1\n$limit2" | sort -g | head -n1 )

cat << EOF > $normal_dir/var-shmem-stashes.mount
# Automatically generated by var-shmem-stashes-generator

[Unit]
Description=Stash mount (/var/shmem/stashes)

After=var-shmem.mount
Requires=var-shmem.mount

[Mount]
What=tmpfs
Where=/var/shmem/stashes
Type=tmpfs
Options=defaults,size=$(printf "%.0f" $min)k,auto
EOF

# In order to make sure the unit is automatically started, we need to symlink it and
# make it a requirement for local-fs.target.

local_fs_target=$normal_dir/local-fs.target.requires

mkdir -p $local_fs_target

ln -sf $normal_dir/var-shmem-stashes.mount $local_fs_target/var-shmem-stashes.mount
