#!/bin/bash

set -euo pipefail

# ensure that the data directory exists before starting licmgrd
if [ ! -d /data/etc/licmgr ]
then
  mkdir -p /data/etc/licmgr
fi

touch /data/etc/licmgr/lservrc
if [ ! -d /data/var/run ]
then
  mkdir -p /data/var/run
fi

if [ ! -d /data/var/revokedb ]
then
  mkdir -p /data/var/revokedb
fi

lroot=/tmp/lroot
lroot_tmp=/run/licmgr-lroot-tmp
mkdir -p "$lroot" "$lroot_tmp"
chmod 1777 "$lroot_tmp"

bind_once()
{
  source=$1
  target=$2

  if ! mountpoint -q "$target"
  then
    mount --bind "$source" "$target"
  fi

  # A bind of a shared source remains shared even below a private parent.
  # Privatize every target so later /run and /var/run submounts cannot
  # propagate into the license root.
  mount --make-rprivate "$target"
}

bind_private_tmp_once()
{
  mkdir -p "$lroot/tmp"

  # The VA 20 OS installer probes /tmp/lroot/tmp/<its temporary mountpoint>.
  # Keep the verifier's chroot but hide host /tmp from it, including when an
  # older wrapper left a different mount at this target.
  if [ "$(stat -Lc '%d:%i' "$lroot_tmp")" != "$(stat -Lc '%d:%i' "$lroot/tmp")" ]
  then
    mount --bind "$lroot_tmp" "$lroot/tmp"
  fi
  mount --make-rprivate "$lroot/tmp"
}

if [ "${1:-}" != "--inside-licmgr-mountns" ]
then
  # Keep the daemon root layout compatible with existing unlock installations.
  # Use non-recursive, idempotent binds so supervised restarts cannot grow the
  # mount tree as the old recursive wrapper did.
  bind_once / "$lroot"
  bind_once /app "$lroot/app"
  bind_once /data "$lroot/data"
  bind_once /proc "$lroot/proc"
  bind_once /sys "$lroot/sys"
  bind_once /dev "$lroot/dev"
  bind_once /run "$lroot/run"
  bind_once /data/var "$lroot/var"
  bind_once /var/run "$lroot/var/run"
  bind_private_tmp_once

  exec /app/running/usr/libexec/licmgr_mountns "$0" --inside-licmgr-mountns
fi
shift

# run license system init
chroot "$lroot" /app/running/usr/libexec/licmgr_init

exec chroot "$lroot" /app/running/usr/libexec/licmgrd
