#!/bin/sh
###############################################################################
##
##  sshtool
##
##
##  2007-01-16  Andreas Vogel (omega)
##
###############################################################################

cmd=$1
dir=$2

sshkeygen=/raid/data/module/SSHD/system/bin/ssh-keygen

SshKey() {
    dir=$1 ; mode=${2:-check} ; filename=$3 ; keytype=$4

    outfile="$dir/$filename"

    if [ "$mode" == force -o ! -f "$outfile" ]; then
        echo "Creating new SSHD host key file: ($keytype) $outfile"

        rm -f "$outfile"
        if ! $sshkeygen -t "$keytype" -f "$outfile" -N "" ; then
            echo "ERROR: cannot generate host key: '$sshkeygen -t "$keytype" -f "$outfile" -N ""'"
            return 1
        fi
    fi
    return 0
}

SshConfig() {
    dir=$1 ; mode=${2:-check}

    if [ "$mode" == force -o ! -f "$dir/sshd_config" ] ; then
        if [ -r "$dir/sshd_config.in" ] ; then
            echo "Creating new SSHD config file: \"$dir/sshd_config\""
            sed -e "s|@CFGDIR@|"$dir"|g" \
                < "$dir/sshd_config.in" \
                > "$dir/sshd_config"
        else
            echo "ERROR: SSHD config template missing: \"$dir/sshd_config.in\""
            return 1
        fi
    fi

    if [ -f "$dir/sshd_config" ] ; then
        chown root.root "$dir/sshd_config"
        chmod 644 "$dir/sshd_config"
    fi
    return 0
}

SshAuthorizedKeys() {
    dir=$1 ; mode=${2:-check}

    if [ "$mode" == force -o ! -f "$dir/authorized_keys" ] ; then
        > "$dir/authorized_keys"
    fi

    if [ -f "$dir/authorized_keys" ] ; then
        chown root.root "$dir/authorized_keys"
        chmod 644 "$dir/authorized_keys"
    fi
    return 0
}

###############################################################################
##
##  Main
##
###############################################################################

if [ ! -d "$dir" ] ; then
    echo "ERROR: cannot open directory '$dir'!"
    exit 1
fi

case "$cmd" in
    checkkeys)
        SshKey "$dir" check ssh_host_key     rsa1 || exit 1
        SshKey "$dir" check ssh_host_dsa_key dsa  || exit 1
        SshKey "$dir" check ssh_host_rsa_key rsa  || exit 1
        ;;

    newkeys)
        SshKey "$dir" force ssh_host_key     rsa1 || exit 1
        SshKey "$dir" force ssh_host_dsa_key dsa  || exit 1
        SshKey "$dir" force ssh_host_rsa_key rsa  || exit 1
        ;;

    checkconfig)
        SshConfig "$dir" check || exit 1
        ;;

    newconfig)
        SshConfig "$dir" force || exit 1
        ;;

    checkauthkeys)
        SshAuthorizedKeys "$dir" check || exit 1
        ;;

    newauthkeys)
        SshAuthorizedKeys "$dir" force || exit 1
        ;;

    *)
        echo "Usage: $0 {checkkeys|newkeys|checkconfig|newconfig|checkauthkeys|newauthkeys} dir"
        exit 1
        ;;
esac

exit 0
