#!/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
        read -r -p "$1 " a
        a=${a:-$2}
        case ${a,,} in y|yes) return 0 ;; n|no) return 1 ;; esac
    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
clear
cat <<'EOF'
==============================================================
  NativeDefence OS - first boot setup
==============================================================
This system ships without any password. Set one for the
administrator account 'ndadmin' (full sudo access) now.

EOF

while true; do
    read -r -s -p "New password for ndadmin: " p1; echo
    read -r -s -p "Repeat password:          " p2; echo
    if [[ -z $p1 || $p1 != "$p2" ]]; then echo "Passwords are empty or do not match."; continue; fi
    if (( ${#p1} < MIN_PW_LEN )); then echo "Use at least $MIN_PW_LEN characters."; continue; fi
    # chpasswd goes through PAM (pam_unix, SHA-512); PAM may reject weak passwords.
    if printf '%s:%s\n' "$ADMIN" "$p1" | chpasswd; then
        break
    fi
    echo "The password was rejected (see the message above). Try another one."
done
unset p1 p2
if ! has_password; then
    echo "Setting the password failed; setup will run again on next boot."
    exit 1
fi

h=$(admin_home)
echo
read -r -p "Paste an SSH public key for ndadmin (Enter to skip): " key
if [[ -n $key ]]; then
    if printf '%s\n' "$key" | ssh-keygen -l -f /dev/stdin >/dev/null 2>&1; then
        install -d -m 700 -o "$ADMIN" -g "$ADMIN" "$h/.ssh"
        printf '%s\n' "$key" >> "$h/.ssh/authorized_keys"
        chown "$ADMIN:$ADMIN" "$h/.ssh/authorized_keys"
        chmod 600 "$h/.ssh/authorized_keys"
        echo "Key added."
    else
        echo "That is not a valid public key; skipped. Add one later from the menu."
    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
