#!/bin/sh
#
# Enable or disable SSH server.
#

. /opt/puzzlefw/lib/functions.sh

# Show current configuration.
show() {

    start_ssh=0
    if [ -f ${CONFIG_DIR}/start_ssh.conf ]; then
        . ${CONFIG_DIR}/start_ssh.conf
    fi

    if [ "${start_ssh}" -eq 1 ]; then
        echo "Current setting: start SSH on boot"
    else
        echo "Current setting: do not start SSH on boot"
    fi

    if [ -f ${CONFIG_DIR}/dropbear_ed25519_host_key ]; then
        dropbearkey -y -f ${CONFIG_DIR}/dropbear_ed25519_host_key
    fi
}

# Generate persistent SSH host key, if necessary.
gen_key() {

    # Do nothing if host key already exists in config partition.
    [ -f ${CONFIG_DIR}/dropbear_ed25519_host_key ] && return

    # If no host key exists, generate it.
    if [ ! -f /etc/dropbear/dropbear_ed25519_host_key ]; then

	echo "Generating SSH host key ..."

        # If /etc/dropbear is a symlink, delete it.
        [ -L /etc/dropbear ] && rm /etc/dropbear

        # Create directory /etc/dropbear if it does not exist.
        mkdir -p /etc/dropbear

        # Generate host key.
        dropbearkey -t ed25519 -f /etc/dropbear/dropbear_ed25519_host_key
    fi

    echo "Writing SSH host key to config partition ..."

    cp -a /etc/dropbear/dropbear_ed25519_host_key ${CONFIG_DIR}/dropbear_ed25519_host_key.new
    sync_config dropbear_ed25519_host_key || exit 1
}

# Enable starting SSH server during boot.
enable() {

    lock_config || exit 1

    gen_key

    echo "Enabling SSH server start on boot ..."

    echo "start_ssh=1" > ${CONFIG_DIR}/start_ssh.conf.new
    sync_config start_ssh.conf || exit 1
}

# Disable starting SSH server during boot.
disable() {

    lock_config || exit 1

    echo "Disabling SSH server start on boot ..."

    echo "start_ssh=0" > ${CONFIG_DIR}/start_ssh.conf.new
    sync_config start_ssh.conf || exit 1
}

case "$1" in
  show)
    show
    ;;
  enable)
    enable
    ;;
  disable)
    disable
    ;;
  *)
    script="${0##*/}"
    cat <<EOF
Usage: $script {enable|disable}"

  $script show
    Show current configuration.

  $script enable
    Enable starting SSH server during boot.

  $script disable
    Disable starting SSH server during boot.

EOF
    exit 1
esac