#!/bin/bash
# @package      hubzero-mw2-front-virtualssh
# @file         populate-sftp
# @author       Pascal Meunier <pmeunier@purdue.edu>
# @copyright    Copyright (c) 2016-2017 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Based on prior work by Richard L. Kennell
#
# Copyright (c) 2016-2017 HUBzero Foundation, LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#

# create the chroot environment for sftp-server to run
# including an empty /etc/passwd that will get entries added as needed

mkdir -p /sftp/usr/lib
mkdir -p /sftp/usr/bin

if [ -f /usr/lib/sftp-server ]; then
  sftp_path=/usr/lib/sftp-server
elif [ -f /usr/libexec/openssh/sftp-server ]; then
  sftp_path=/usr/libexec/openssh/sftp-server
fi

cd /sftp
ldd $sftp_path | sed 's,^[^/]*\(/.*\)[ ].*$,\1,' | grep -v vdso | \
xargs /bin/tar -ch -f - 2>/dev/null | (cd /sftp; /bin/tar -xpf - )


cmp -s $sftp_path /sftp/usr/lib/sftp-server || {
  cp -aL $sftp_path /sftp/usr/lib
}

mkdir -p /sftp/usr/bin
cmp -s /usr/bin/scp /sftp/usr/bin/scp || {
  cp -aL /usr/bin/scp /sftp/usr/bin
}

# copying more than necessary to be sure it works.
# package libnss-ldapd provides libnss_ldap.so.2 instead
# libc6: /lib/libnss_compat.so.2  for Debian Squeeze
ls /lib/libnss_* 2>/dev/null >/dev/null
if [ $? -eq 0 ]; then
  cp -aL /lib/libnss_* /sftp/lib
fi

# libc6 2.13-37 has a different path in Debian Wheezy
# /lib/x86_64-linux-gnu/libnss_compat.so.2
if [ -d /lib/x86_64-linux-gnu ]; then
  mkdir -p /lib/x86_64-linux-gnu
  cp -aL /lib/x86_64-linux-gnu/libnss_* /sftp/lib/x86_64-linux-gnu
fi

mkdir -p /sftp/dev
cp -a /dev/null /sftp/dev
chmod 666 /sftp/dev/null

mkdir -p /sftp/etc
touch /sftp/etc/passwd
cp -a /etc/localtime /sftp/etc
