#!/bin/bash
# NDOS first-boot provisioning.
#
# One image, three platforms:
#   AWS EC2 (AMI) : key login only. cloud-init puts the customer's EC2 key pair
#                   into ~ndadmin/.ssh/authorized_keys; this script enables sshd.
#                   SSH password login stays OFF (AWS Marketplace rule).
#   Bare metal / VM : SSH password login is turned ON (drop-in below), because
#                   there is no EC2 key pair. If cloud-init already provisioned
#                   a key or password, accept it; otherwise the operator sets the
#                   ndadmin password on the console, may add an SSH key, and
#                   chooses whether sshd is enabled.
#
# The image itself ships with no password hashes and no keys, and its
# sshd_config says "PasswordAuthentication no". On bare metal / VMs the drop-in
# /etc/ssh/sshd_config.d/40-nd-password.conf overrides that with "yes".
set -u

FLAG=/etc/nd/provisioned
ADMIN=ndadmin
PW_DROPIN=/etc/ssh/sshd_config.d/40-nd-password.conf
MIN_PW_LEN=12

log() { echo "nd-firstboot: $*"; logger -t nd-firstboot -- "$*" 2>/dev/null || true; }

is_ec2() {
    grep -qi 'amazon' /sys/class/dmi/id/sys_vendor 2>/dev/null && return 0      # Nitro
    grep -q '^i-' /sys/class/dmi/id/board_asset_tag 2>/dev/null && return 0     # Nitro
    grep -qi 'amazon' /sys/class/dmi/id/bios_version 2>/dev/null && return 0    # Xen
    grep -qi '^ec2' /sys/hypervisor/uuid 2>/dev/null && return 0                # Xen
    return 1
}

admin_home() { getent passwd "$ADMIN" | cut -d: -f6; }
has_key()      { local h; h=$(admin_home); [ -n "$h" ] && [ -s "$h/.ssh/authorized_keys" ]; }
has_password() { local p; p=$(getent shadow "$ADMIN" | cut -d: -f2); [[ $p == \$* ]]; }

finish() {
    install -d -m 0755 /etc/nd
    date -u +%Y-%m-%dT%H:%M:%SZ > "$FLAG"
    log "provisioning complete"
}

enable_password_ssh() {
    install -d -m 0755 /etc/ssh/sshd_config.d
    printf 'PasswordAuthentication yes\n' > "$PW_DROPIN"
    chmod 0644 "$PW_DROPIN"
    log "SSH password login enabled (not an AWS instance)"
}

start_sshd() {
    ssh-keygen -A >/dev/null 2>&1      # fill in missing host keys only
    if sshd -t; then
        systemctl enable sshd.service >/dev/null 2>&1
        systemctl start --no-block sshd.service
    else
        log "sshd -t failed; sshd not started"
    fi
}

ask_yn() {  # ask_yn "question" default(y|n)
    local a
    while true; do
        printf '%s ' "$1"
	read -r a || a=""
        a=${a:-$2}
        case ${a,,} in y|yes) return 0 ;; n|no) return 1 ;; esac
    done
}

quiet_console() {
    # Keep boot status lines and kernel messages from writing over the prompts.
    kill -SIGRTMIN+21 1 2>/dev/null || true    # systemd: stop printing status lines
    dmesg -n 1 2>/dev/null || true             # kernel: only emergency messages
}

drain_input() {
    # Throw away keys pressed while the system was booting.
    while read -r -t 0.2 -n 1024 _junk; do :; done
}

# --------------------------------------------------------------------- EC2 --
if is_ec2; then
    rm -f "$PW_DROPIN"                 # Marketplace: never password SSH on EC2
    start_sshd
    if has_key; then
        finish
    else
        log "EC2 instance launched without a key pair; will check again next boot"
    fi
    exit 0
fi

# ------------------------------- not AWS: password SSH on (bare metal / VM) --
enable_password_ssh

# ------------------------------------------- already provisioned elsewhere --
if has_key || has_password; then
    log "admin credentials already present (cloud-init or earlier setup)"
    start_sshd
    finish
    exit 0
fi

# ------------------------------------------------- interactive (console) ----
if [ ! -t 0 ]; then
    log "no console attached and no credentials provisioned; will run again next boot"
    exit 1
fi
quiet_console
drain_input
clear
cat <<'EOF'
==============================================================
  NativeDefence OS - first boot setup
==============================================================
This system ships without any password. Set one for the
administrator account 'ndadmin' now.

EOF
echo "The password must be at least $MIN_PW_LEN characters long."
echo

while true; do
    drain_input
    printf 'Enter password for ndadmin: '
    if ! IFS= read -r -s p1; then
        echo; log "console input closed during password setup; will run again next boot"; exit 1
    fi
    echo
    if [[ -z $p1 ]]; then
        echo "The password cannot be empty."; echo; continue
    fi
    if (( ${#p1} < MIN_PW_LEN )); then
        echo "Too short (${#p1} characters). Use at least $MIN_PW_LEN characters."; echo; continue
    fi
    printf 'Confirm password: '
    IFS= read -r -s p2 || p2=""
    echo
    if [[ $p1 == *[[:cntrl:]]* ]]; then
        echo "The password cannot contain control characters."; echo; continue
    fi
    if [[ $p1 != "$p2" ]]; then
        echo "The passwords do not match. Please try again."; echo; continue
    fi
    # chpasswd goes through PAM (pam_unix, SHA-512); PAM may reject weak passwords.
    if printf '%s:%s\n' "$ADMIN" "$p1" | chpasswd; then
        echo "Password set."
        break
    fi
    echo "The password was rejected (see the message above). Try another one."; echo
done
unset p1 p2
if ! has_password; then
    echo "Setting the password failed; setup will run again on next boot."
    exit 1
fi

echo
printf 'Paste an SSH public key for ndadmin (Enter to skip): '
read -r key || key=""
if [[ -n ${key//[[:space:]]/} ]]; then
    # Same checks as menu option 16 (type, base64, no options, key size)
    if printf '%s\n' "$key" | /usr/sbin/nd-ssh-auth add-key; then
        :    
    else
	echo "Key skipped. Add one later from the menu (option 16)."
    fi
fi
unset key

echo
if ask_yn "Enable SSH access now (port 2224, password or key login)? [Y/n]" y; then
    start_sshd
else
    systemctl disable sshd.service >/dev/null 2>&1
    echo "SSH stays off. Enable it later from the menu (option 9)."
fi

finish
echo
echo "Setup done. Log in on the console as 'ndadmin'."
sleep 2
exit 0
