#!/bin/bash

userConfPath="/etc/sftp-users.conf"
userConfFinalPath="/var/run/sftp-users.conf"

function printHelp() {
    echo "Add users as command arguments, STDIN or mounted in $userConfPath"
    echo "Syntax: user:pass[:e][:uid[:gid]]..."
    echo "Use --readme for more information and examples."
}

function printReadme() {
    cat /README.md
    echo "TIP: Read this in HTML format here: https://github.com/atmoz/sftp"
}

function createUser() {
    IFS=':' read -a param <<< $@
    user="${param[0]}"
    pass="${param[1]}"

    if [ -z "$user" ]; then
        echo "You must at least provide a username."
        printHelp
        exit 1
    fi

    if [ "${param[2]}" == "e" ]; then
        chpasswdOptions="-e"
        uid="${param[3]}"
        gid="${param[4]}"
    else
        uid="${param[2]}"
        gid="${param[3]}"
    fi

    useraddOptions="--no-user-group"

    if [ -n "$uid" ]; then
        useraddOptions="$useraddOptions --non-unique --uid $uid"
    fi

    if [ -n "$gid" ]; then
        useraddOptions="$useraddOptions --gid $gid"

        if [ "$(cat /etc/group | cut -d : -f3 | grep -q "$gid")" ]; then
            groupadd --gid $gid $gid
        fi
    fi

    useradd $useraddOptions $user
    chown root:root /home/$user
    chmod 755 /home/$user

    if [ -z "$pass" ]; then
        pass="$(echo `</dev/urandom tr -dc A-Za-z0-9 | head -c256`)"
        chpasswdOptions=""
    fi

    echo "$user:$pass" | chpasswd $chpasswdOptions

    cat /home/$user/.ssh/keys/* >> /home/$user/.ssh/authorized_keys
    chown $user /home/$user/.ssh/authorized_keys
    chmod 600 /home/$user/.ssh/authorized_keys
}

if [[ $1 =~ ^--help$|^-h$ ]]; then
    printHelp
    exit 0
fi

if [ "$1" == "--readme" ]; then
    printReadme
    exit 0
fi

# Append mounted config to final config
if [ -f "$userConfPath" ]; then
    cat "$userConfPath" >> "$userConfFinalPath"
fi

# Append users from arguments to final config
for user in "$@"; do
    echo "$user" >> "$userConfFinalPath"
done

# Append users from STDIN to final config
while IFS= read -r user || [[ -n "$user" ]]; do
    echo "$user" >> "$userConfFinalPath"
done

if [ ! -f "$userConfFinalPath" ]; then
    echo "ERROR: Missing users!"
    printHelp
    exit 1
fi

# Import users from final conf file
while IFS= read -r user || [[ -n "$user" ]]; do
    createUser "$user";
done < "$userConfFinalPath"

exec /usr/sbin/sshd -D