#!/bin/bash
usage() {
    echo "Usage: $0 [-r] [-k]"
    echo "       -r: Not to use container"
    echo "       -k: Use previously generated key, not to generate new key"
    echo "Environment variables"
    echo " SINGULARITY_CONTAINER: Singularity container SIF file path"
    echo " SINGULARITY_BIND: Container mounted directories from the host"
    echo " SINGULARITY_ENVIRONMENT: Environment variables passed to the container"
    exit 1
}

container=1
keygen=1

while [ $# != '0' ]; do
    case $1 in
    -r)
        container=0
        ;;
    -k)
        keygen=0
        ;;
    -h)
        usage ;;
    *)
        echo "Invalid option"
        usage ;;
    esac
    shift
done

umask 0022
SSHDIR=$HOME/.ssh
if [ $container == 1 ]; then
    if [ -z $SINGULARITY_CONTAINER ]; then
        SINGULARITY_CONTAINER=/share/apps/containers/centos7.sif
    fi
    if [ -z $SINGULARITY_BIND  ]; then
        SINGULARITY_BIND=/opt,/lib64,/usr,/share,/etc/profile.d,/etc/ld.so.cache
    fi
    if [ -z $SINGULARITY_ENVIRONMENT ]; then
        SINGULARITY_ENVIRONMENT=PATH=/usr/bin:/opt/skyformai/bin
    fi
    if ! which singularity > /dev/null 2>&1; then
        echo Please install singularity-ce
        exit 1
    fi

    if [ ! -f $SINGULARITY_CONTAINER ]; then
        echo The container image file $SINGULARITY_CONTAINER does not exist
        exit 1
    fi
fi

if [ -z $CB_JOBID ] || [ -z "$CB_ALLOCATION" ]; then
    echo Please run it as an AIP job
    exit 1
fi

port=$(echo $CB_ALLOCATION | awk -F '"Port":' '{print $2}' | cut -d'}' -f1 | cut -d',' -f1)
hostname=$(hostname)
SSHD_CONFIG=$SSHDIR/sshd_config.$hostname.$port
SSHD_LOG=$SSHDIR/sshd.$hostname.$port.log
if [ $container == 0 ]; then
    CMD="/usr/sbin/sshd -p $port -f $SSHD_CONFIG -D -E $SSHD_LOG"
else
    CMD="singularity run --pid --env $SINGULARITY_ENVIRONMENT $SINGULARITY_CONTAINER /usr/sbin/sshd -p $port -f $SSHD_CONFIG -D -E $SSHD_LOG"
fi

# create sshd required files
if [ ! -d $SSHDIR ]; then
    mkdir -p $SSHDIR
fi
AUTHORIZEDKEYS=.ssh/authorized_keys.$hostname.$port
if [ ! -f $SSHD_CONFIG ]; then
    for method in ecdsa ed25519 rsa; do
        if [ ! -f $SSHDIR/ssh_host_${method}_key ]; then
           ssh-keygen -t $method -f $SSHDIR/ssh_host_${method}_key -N "" -q
        fi
    done
    cat <<EOF > $SSHD_CONFIG
HostKey $SSHDIR/ssh_host_rsa_key
HostKey $SSHDIR/ssh_host_ecdsa_key
HostKey $SSHDIR/ssh_host_ed25519_key
PidFile $SSHDIR/sshd.pid
SyslogFacility AUTHPRIV
AuthorizedKeysFile $AUTHORIZEDKEYS
PasswordAuthentication no
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM no
X11Forwarding yes
UsePrivilegeSeparation no
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem sftp /usr/libexec/openssh/sftp-server
EOF
    chmod 600 $SSHD_CONFIG
fi
if [ $keygen == 1 ] || [ ! -f $HOME/$AUTHORIZEDKEYS ]; then
    # generate key
    ssh-keygen -f $SSHDIR/key -N "" -q
    mv $SSHDIR/key.pub $HOME/$AUTHORIZEDKEYS

    # cat key, remove private key
    cat $SSHDIR/key
    rm $SSHDIR/key
else
    echo Please use existing key
fi
ip=$(grep $(hostname -s) $CB_ENVDIR/hosts | awk '{print $1}')
user=$(id -u -n)

if [ -f $CB_ENVDIR/jumpserver.yaml ]; then
    #jumpserver
    pubip=$(grep ^pubip $CB_ENVDIR/jumpserver.yaml| cut -d' ' -f2)
    pubport=$(grep ^pubport $CB_ENVDIR/jumpserver.yaml| cut -d' ' -f2)
    jumpkeydir=$(grep ^jumpkeydir $CB_ENVDIR/jumpserver.yaml| cut -d ' ' -f2)
fi
if [ ! -z $pubip ] && [ ! -z $pubport ] && [ ! -z $jumpkeydir ] && [ -d $jumpkeydir ]; then
    mkdir -p $jumpkeydir/$user
    chmod 700 $jumpkeydir/$user
    cat $SSHDIR/authorized_keys.*.* > $jumpkeydir/$user/authorized_keys
    pubmessage="-J $user@$pubip:$pubport $user@$ip -p $port"
else
    # proxy
    proxyconf $ip $port > $SSHDIR/ports.$port
    pubip=$(cat $SSHDIR/ports.$port | awk '{print $1}')
    pubport=$(cat $SSHDIR/ports.$port | awk '{print $2}')
    pubmessage="-p $pubport $user@$pubip"
fi
if [ $pubip != $ip ] || [ $pubport != $port ]; then
    private="; ssh -i key -p $port $user@$ip"
fi
cpost -d "ssh -i key $pubmessage$private" $CB_JOBID > /dev/null 2>&1
rm -f $SSHD_LOG
exec $CMD
