# copied from https://github.com/concourse/concourse/blob/f4b40a18b94ed816cea7dfba20ad365bb566483b/jobs/baggageclaim/templates/baggageclaim_ctl.erb#L23-L54
# # break out of bosh-lite device limitations
function permit_device_control() {
  local devices_mount_info=$(cat /proc/self/cgroup | grep devices)

  if [ -z "$devices_mount_info" ]; then
    # cgroups not set up; must not be in a container
    return
  fi

  local devices_subsytems=$(echo $devices_mount_info | cut -d: -f2)
  local devices_subdir=$(echo $devices_mount_info | cut -d: -f3)

  if [ "$devices_subdir" = "/" ]; then
    # we're in the root devices cgroup; must not be in a container
    return
  fi

  if ! mountpoint /tmp/devices-cgroup &> /dev/null; then
    # mount our container's devices subsystem somewhere
    mkdir -p /tmp/devices-cgroup
    mount -t cgroup -o $devices_subsytems none /tmp/devices-cgroup
  fi

  # permit our cgroup to do everything with all devices
  if ! echo a > /tmp/devices-cgroup${devices_subdir}/devices.allow && [ ! -d "/run/systemd/system" ]; then
    # ensure this log line goes to stderr
      >&2 echo "Could not permit all devices. This is normal in non systemd mode."
  fi

  if mountpoint /tmp/devices-cgroup &> /dev/null; then
    umount /tmp/devices-cgroup 2>&1 || true
  fi
}

function create_loop_devices() {
  LOOP_CONTROL=/dev/loop-control
  if [ ! -c $LOOP_CONTROL ]; then
    mknod $LOOP_CONTROL c 10 237
    chown root:disk $LOOP_CONTROL
    chmod 660 $LOOP_CONTROL
  fi

  amt=$1
  for i in $(seq 0 $amt); do
    if [ ! -e /dev/loop$i ]; then
      mknod -m 0660 /dev/loop$i b 7 $i 2>&1 || true
    fi
  done
}

function load_apparmor_profile() {
  local profile_path=$1
  export PATH=$PATH:$(readlink -nf /var/vcap/packages/apparmor/bin)

  if ! mountpoint -q /sys/kernel/security; then
    mount -t securityfs securityfs /sys/kernel/security
  fi

  apparmor_parser -r "$profile_path"
}

function disable_transparent_hugepages() {
  if ! echo madvise > /sys/kernel/mm/transparent_hugepage/enabled ; then
    # ensure this log line goes to stderr
    >&2 echo "Could not disable automatic transparent hugepage allocation. This is normal in bosh lite."
  fi
}

function restrict_dmesg_access() {
  echo 1 > /proc/sys/kernel/dmesg_restrict
}

function increase_max_open_fds() {
  ulimit -n 65536
}

function increase_max_procs() {
  echo 4194304 > /proc/sys/kernel/pid_max
  ulimit -u unlimited
}
