#!/bin/bash

set +e

# chkHostname
/usr/lib/raspberrypi-sys-mods/imager_custom \
  set_hostname \
    {{HOSTNAME}}

# chkSetUser - passwords hashes out to 'raspberry'
/usr/lib/userconf-pi/userconf \
  '{{USERNAME}}' \
  '$6$bJN6rc42S4by69dC$O1RXFgeQdhyKXh0As8fwP8QbKf4NCwUgAee0P9SowTdOG3bNxSdypU0.a0mX2yXLuJqTHHGm1HNr.Pm1UftEW1' 

# chkSSH
/usr/lib/raspberrypi-sys-mods/imager_custom \
  enable_ssh \
    -p \
    '{{SSH_KEY}}'

# Ensure SSH key is properly deployed (manual backup method)
mkdir -p /home/{{USERNAME}}/.ssh
echo '{{SSH_KEY}}' >> /home/{{USERNAME}}/.ssh/authorized_keys
chmod 700 /home/{{USERNAME}}/.ssh
chmod 600 /home/{{USERNAME}}/.ssh/authorized_keys
chown -R {{USERNAME}}:{{USERNAME}} /home/{{USERNAME}}/.ssh

# Configure SSH security: disable password authentication, enable key-only access
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config  
sed -i 's/PubkeyAuthentication no/PubkeyAuthentication yes/' /etc/ssh/sshd_config

# Additional SSH security hardening
echo "ChallengeResponseAuthentication no" >> /etc/ssh/sshd_config
echo "UsePAM yes" >> /etc/ssh/sshd_config

# chkWifi
/usr/lib/raspberrypi-sys-mods/imager_custom \
  set_wlan \
    '{{WLAN_SSID}}' \
    '{{WLAN_PASSWORD}}' \
    'GB'

# chkLocale
/usr/lib/raspberrypi-sys-mods/imager_custom \
  set_keymap \
    'gb'
/usr/lib/raspberrypi-sys-mods/imager_custom \
  set_timezone \
    'GB'

# firstrun
rm -f /boot/firstrun.sh
sed -i 's| systemd.run.*||g' /boot/cmdline.txt
exit 0
