#!/bin/bash

# Create a chroot for an SSH user for apt read only access
USER=$1
CHROOT=/home/$1
useradd $USER
chown root.root -R $CHROOT

# Specific permission for .ssh 
mkdir -m 750 $CHROOT/.ssh
touch $CHROOT/.ssh/authorized_keys
chmod 640 $CHROOT/.ssh/authorized_keys
chgrp -R $USER $CHROOT/.ssh

###
### to do by hand or by playbook
###

## configure ssh for chrooting user
#cat <<EOF >> /etc/ssh/sshd_config
## Added for chroot 
#Match User $USER
#ChrootDirectory $CHROOT
#EOF
#
## predisporre bind mount del repo
#echo /home/reprepro/repo $CHROOT/debian none bind 0 0  >> /etc/fstab
## aggingere le chiavi necessarie
# echo ssh-rsa XXXXX id > $CHROOT/.ssh/authorized_keys

# prepare chroot
mkdir $CHROOT/{debian,dev,lib,lib64,bin,lib/x86_64-linux-gnu}

mknod -m 666 $CHROOT/dev/null c 1 3
mknod -m 666 $CHROOT/dev/tty c 5 0
mknod -m 666 $CHROOT/dev/zero c 1 5
mknod -m 666 $CHROOT/dev/random c 1 8

COMMANDS="bash sh dd find"

j=""
for i in $COMMANDS; do
   j="$j$(which $i) "
done

# copy command
for i in $j; do
    cp $i $CHROOT/bin/
done

# get command shared libs
LIST=$(for i in $j; do ldd $j; done |grep '=>'|awk '{print $3}'|sort|uniq)

# copy shared libs in chroot
for i in $LIST; do
   cp $i $CHROOT/lib/x86_64-linux-gnu/
done

# copy this also
cp /lib64/ld-linux-x86-64.so.2 $CHROOT/lib64/
