#!/bin/bash
### mount-tb.sh  -*- Sh -*-
## Bind-mount directories below a given one under timestamp-based names.

### Ivan Shmakov, 2019

## To the extent possible under law, the author(s) have dedicated
## all copyright and related and neighboring rights to this software
## to the public domain worldwide.  This software is distributed
## without any warranty.

## You should have received a copy of the CC0 Public Domain Dedication
## along with this software.  If not, see
## <http://creativecommons.org/publicdomain/zero/1.0/>.

### History:

## 0.2  2019-09-15
##      Now a separate program (was: a function in .bash.func.)

## 0.1  2019-09-14
##      Initial revision.

### Commentary:

##  Example:
##    # mount-tb  /tmp/stage.to \
##          private/users/joe/private/bits/foo-"$(date +%Y)" \
##          =/tmp/stage.from 

### Code:

set -e
set -C -u

if ! test "$#" -ge 3 ; then
    printf %s\\n "Usage: sh ${0##*/}  PREFIX SUFFIX DIRECTORY..." >&2
    ## .
    exit 1
fi

pfx=${1}
sfx=${2}
shift 2

# d1 d2 d ts e1 e
for d1 ; do
    ts=x$(printf %08x\\n "$(date -u +%s)")
    ## NB: using Bash-specific ${varn//from/to} substitution
    case "$d1" in
        (*=*) e1=${d1%%=*} ; e=${pfx}/${e1:+${e1}-}${ts} ; d=${d1#*=} ;;
        (*)   d2=${d1#/}   ; e=${pfx}/${d2//\//_}-${ts}  ; d=${d1} ;;
    esac
    e=${e%/}/${sfx%/}
    mkdir -p -- "$e"
    mount --bind -- "$d" "$e"
done

### mount-tb.sh ends here
