#!/bin/bash -e

SSDCOUNT=0
for DISK in /sys/block/sd*; do
    if grep -q 0 "${DISK}/queue/rotational" 2>/dev/null; then
        SSD="/dev/$(basename "${DISK}")"
        if [ -v BTRPARTS ]; then
            BTRPARTS="${BTRPARTS} ${SSD}1"
        else
            BTRPARTS="${SSD}1"
        fi
        ((SSDCOUNT++)) || true
        echo "2MiB +" | sfdisk -w always -q "${SSD}"
    fi
done

case "${SSDCOUNT}" in
1)
    mkfs.btrfs -L rootfs -f ${BTRPARTS}
    ;;
2)
    mkfs.btrfs -L rootfs -f -d raid1 ${BTRPARTS}
    ;;
4)
    mkfs.btrfs -L rootfs -f -d raid10 ${BTRPARTS}
    ;;
6)
    mkfs.btrfs -L rootfs -f -d raid10 ${BTRPARTS}
    ;;
esac

WORK_DIR="/mnt/rootfs"
mkdir -p /mnt/rootfs
mount -L rootfs /mnt/rootfs
mkdir -p /mnt/rootfs/tmp /mnt/rootfs/proc /mnt/rootfs/sys /mnt/rootfs/var /mnt/rootfs/dev

cd /mnt/rootfs
btrfs subvol create snaps || true
btrfs subvol create home || true
btrfs subvol create srv || true
btrfs subvol create var/log || true

for DIR in /bin /boot /etc /home /lib /lib64 /root /sbin /usr /var; do
    rsync -ac "${DIR}" /mnt/rootfs/
done

mkdir -p run mnt

echo "LABEL=rootfs / btrfs defaults 0 1" > /mnt/rootfs/etc/fstab

SERIAL_PORT="$(lsof | grep -vi grep | grep /dev/ttyS | head -n 1 | awk '{ print $NF }')"

if [ -z "$SERIAL_PORT" ]; then
    SERIAL_PORT=0
fi

LINUX_SERIAL_PORT="$(echo "${SERIAL_PORT}" | cut -d/ -f 3)" || true
GRUB_SERIAL_PORT="$(echo "${SERIAL_PORT}" | cut -dS -f 2)" || true

sed 's/GRUB_CMDLINE_LINUX.*$//' -i /mnt/rootfs/etc/default/grub

cat <<EOF >> /mnt/rootfs/etc/default/grub
GRUB_TERMINAL=serial
GRUB_SERIAL_COMMAND="serial --speed=115200 --unit=${GRUB_SERIAL_PORT} --word=8 --parity=no --stop=1"
GRUB_CMDLINE_LINUX_DEFAULT="console=${LINUX_SERIAL_PORT},115200n8"
GRUB_CMDLINE_LINUX=""

EOF

mkdir -p "${WORK_DIR}/etc/systemd/resolved.conf.d"
mkdir -p "${WORK_DIR}/etc/systemd/network"
mkdir -p "${WORK_DIR}/etc/systemd/system/systemd-networkd.service.d"

cat <<EOF > "${WORK_DIR}/etc/systemd/system/systemd-networkd.service.d/10-debug.conf"
Environment=SYSTEMD_LOG_LEVEL=info

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/resolved.conf.d/search.conf"
[Resolve]
Domains=carmickle.com

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/10-vm-dhcp.network"
[Match]
Virtualization=yes
Name=en*

[Link]
RequiredForOnline=no

[Network]
DHCP=ipv4
IPv6AcceptRA=yes
IPv6PrivacyExtensions=no
IPv6LinkLocalAddressGenerationMode=persistent

[IPv6AcceptRA]
UseDNS=yes
UseDomains=yes

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/25-bond1.netdev"
[Match]
Virtualization=no

[NetDev]
Name=bond1
Kind=bond

[Bond]
Mode=802.3ad
TransmitHashPolicy=layer3+4
LACPTransmitRate=fast
MIIMonitorSec=0.1
UpDelaySec=0.2
DownDelaySec=0.2
MinLinks=1

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/25-bond1.link"
[Match]
Type=bond
Virtualization=no

[Link]
MACAddressPolicy=persistent
MTUBytes=9152
Duplex=full
BitsPerSecond=2G

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/25-bond1.network"
[Match]
Name=bond1

[Link]
RequiredForOnline=no
Unmanaged=no

[Network]
VLAN=vlan682
LinkLocalAddressing=no
DHCP=no
IPv6AcceptRA=false
IPv6PrivacyExtensions=no
IPv6LinkLocalAddressGenerationMode=none
BindCarrier=en*
ConfigureWithoutCarrier=true

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/25-bond1-devs.network"
[Match]
Virtualization=no
Property=!ID_MODEL_ID=0x10d3
Name=en*

[Network]
Bond=bond1
VLAN=vlan682

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/26-vlan682.netdev"
[NetDev]
Name=vlan682
Kind=vlan

[VLAN]
Id=682

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/26-vlan682.network"
[Match]
Name=vlan682

[Network]
DHCP=no
IPv6AcceptRA=yes
IPv6PrivacyExtensions=false
IPv6LinkLocalAddressGenerationMode=persistent
LinkLocalAddressing=IPv6

[IPv6AcceptRA]
UseDNS=yes
UseDomains=yes

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/50-baremetal-dhcp.network"
[Match]
Virtualization=no
Property=ID_MODEL_ID=0x10d3
Name=en*

[Link]
RequiredForOnline=no

[Network]
DHCP=yes

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/80-wg.netdev"
[NetDev]
Kind=wireguard
Name=wg0
MTUBytes=1350

[WireGuard]
PrivateKeyFile=/etc/wireguard/wg0.key
ListenPort=51820

[WireGuardPeer]
PublicKey=w27atMR+cSc+uNqZlH/6B2egUlx0gVAsGV658e7tjRI=
AllowedIPs=2001:470:1f07:6f1::/64, 2001:470:8a7a::/48, 2600:3c03:e000:3c2::55:32/128, 0.0.0.0/0
Endpoint=mobile.carmickle.com:51820
PersistentKeepalive=25

[WireGuardPeer]
PublicKey=Yk1cWDbQC4tUUjTeb3TGMuzX9SRclohW+mTuf2/HYnU=
AllowedIPs=::/0, 100.64.0.0/16
Endpoint=wg6.carmickle.com:51820

[WireGuardPeer]
PublicKey=T8zNzd3K6NxARNZ43D9l6TFq8ytFEYKMH1yHNjzgFnI=
AllowedIPs=fe80::/10
Endpoint=dnsmas01.carmickle.com:51820

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/network/80-wg.network"
[Match]
Name=wg0

[Network]
IPv6Token=prefixstable

[Route]
Destination=::/0
Gateway=2600:3c03:e000:3c2::1
Metric=256

[Route]
Destination=2001:470:8a7a::/48
Gateway=2600:3c03:e000:3c2::55:32
Metric=256

[Route]
Destination=2001:470:1f07:6f1::/64
Gateway=2600:3c03:e000:3c2::55:32
Metric=256

[Route]
Destination=100.127.255.0/24
Gateway=100.65.55.32

EOF

chroot "${WORK_DIR}" chmod 600 "/etc/systemd/network/80-wg.netdev"
chroot "${WORK_DIR}" chown systemd-network "/etc/systemd/network/80-wg.netdev"

rm -f "${WORK_DIR}/etc/resolv.conf"

chroot "${WORK_DIR}" systemctl disable networking 2>/dev/null || true
chroot "${WORK_DIR}" systemctl enable systemd-networkd || true
chroot "${WORK_DIR}" systemctl enable systemd-resolved.service || true

ln -sf /run/systemd/resolve/stub-resolv.conf "${WORK_DIR}/etc/resolv.conf"

# Generate the locales we actually use. mmdebstrap installs the
# `locales` package but doesn't run locale-gen, so /usr/lib/locale
# ships empty and anything that calls setlocale(LANG=en_US.UTF-8)
# falls back to C with warnings. Enable en_US.UTF-8 in
# /etc/locale.gen, compile, then pin LANG=en_US.UTF-8 in
# /etc/default/locale. (C / C.UTF-8 are built into glibc 2.35+ and
# do not need locale-gen; trixie's glibc has them already.)
sed -i 's/^# *en_US\.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' \
  "${WORK_DIR}/etc/locale.gen"
chroot "${WORK_DIR}" locale-gen
cat <<EOF > "${WORK_DIR}/etc/default/locale"
LANG=en_US.UTF-8
EOF

# Fail the build if en_US.UTF-8 didn't actually get compiled — better
# to catch it here than ship an image that emits locale warnings on
# every login.
if ! chroot "${WORK_DIR}" locale -a 2>/dev/null | grep -qi '^en_US\.utf8$'; then
  echo "error: en_US.UTF-8 locale not present after locale-gen" >&2
  exit 1
fi

cat <<EOF > "${WORK_DIR}/etc/hostname"
unconfigured
EOF

echo "::1 unconfigured" >> "${WORK_DIR}/etc/hosts"

chroot "${WORK_DIR}" passwd -d root

# Allow empty-password console login for root. Two Debian defaults
# block it: pam_securetty restricts root to TTYs in /etc/securetty
# (rejecting before any password prompt), and pam_unix without
# `nullok` rejects empty passwords. Both need to give. Without these
# edits, the operator types "root" at the serial console, PAM
# silently rejects, getty respawns, login prompt loops. This matches
# the README's "console access is operator access by design" intent.
# Safe: sshd_config (later in this file) sets PasswordAuthentication
# no, so the network surface is unaffected.

# 1) Comment out pam_securetty (TTY-allowlist for root) in login's
#    PAM stack. Match any active auth line using pam_securetty; Debian
#    has changed the control word across releases, and any active
#    pam_securetty entry can reject ttyS* before a password prompt.
if [[ -f "${WORK_DIR}/etc/pam.d/login" ]]; then
  sed -i -E 's#^([[:space:]]*auth[[:space:]].*pam_securetty\.so.*)$#\# \1#' \
    "${WORK_DIR}/etc/pam.d/login"
fi

# 2) Add `nullok` to the pam_unix.so auth line in common-auth so the
#    empty shadow entry that `passwd -d root` produces is accepted.
#    awk is more forgiving than sed across pam_unix.so line variants
#    (extra options after pam_unix.so, tabs vs spaces, trailing
#    whitespace, etc.) — match any auth line invoking pam_unix.so
#    that doesn't already have nullok, and append nullok at EOL.
awk '
  /^auth[[:space:]].*pam_unix\.so/ && !/nullok/ { sub(/[[:space:]]*$/, ""); $0 = $0 " nullok" }
  { print }
' "${WORK_DIR}/etc/pam.d/common-auth" > "${WORK_DIR}/etc/pam.d/common-auth.new"
mv "${WORK_DIR}/etc/pam.d/common-auth.new" "${WORK_DIR}/etc/pam.d/common-auth"

# 3) Verify both edits took effect; refuse to build a broken image.
if grep -qE '^[[:space:]]*auth[[:space:]].*pam_securetty\.so' \
   "${WORK_DIR}/etc/pam.d/login" 2>/dev/null; then
  echo "error: pam_securetty.so still active in /etc/pam.d/login — console root login will be denied" >&2
  exit 1
fi
if ! grep -qE '^auth[[:space:]].*pam_unix\.so.*nullok' \
     "${WORK_DIR}/etc/pam.d/common-auth"; then
  echo "error: nullok not present on pam_unix.so auth line in common-auth — console root login will be denied" >&2
  exit 1
fi

chroot "${WORK_DIR}" ln -s /lib/systemd/systemd /init || true
chroot "${WORK_DIR}" useradd -c "Frank Carmickle" -m -G sudo,adm,staff -s /bin/bash frankiec || true
chroot "${WORK_DIR}" passwd -l frankiec
mkdir -p "${WORK_DIR}/home/frankiec/.ssh/"
chroot "${WORK_DIR}" chown -R frankiec: /home/frankiec
chroot "${WORK_DIR}" chmod 700 /home/frankiec/.ssh

cat <<EOF > "${WORK_DIR}/home/frankiec/.ssh/authorized_keys"
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILtS3iD0cskYX68Gry7CHJVkqBNxPko1qKH9sW/yPjKz frankiec@fcmbp11
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDZdr0mZysFrgiEozuGMaQ8G4K9EA4gyyKV0MumlRbL3 frankiec@fcsid14
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFcchAVIbIAtJ/zGZ6tvGZTw/9ns+yDC3O98BVQVzYDy frankiec@tv22

EOF

cat <<EOF > "${WORK_DIR}/home/frankiec/.mg"
make-backup-files
backup-to-home-directory

EOF

cat <<EOF > "${WORK_DIR}/root/.mg"
make-backup-files
backup-to-home-directory

EOF

cat <<EOF > "${WORK_DIR}/home/frankiec/.bashrc"
# ~/.bashrc: executed by bash(1) for non-login shells.
case \$- in
    *i*) ;;
      *) return;;
esac

HISTCONTROL=ignoreboth
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize

[ -x /usr/bin/lesspipe ] && eval "\$(SHELL=/bin/sh lesspipe)"

if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

alias emacs='/usr/bin/mg '
alias ls='ls -1F '
alias day='/bin/date +%Y%m%d -u '
alias mem='ps --sort -rss -eo rss,pid,tty,command | head '
alias datetime='/bin/date +%Y%m%d%k%M -u'
export LESS="-CiMR~X"
export VISUAL=mg
export EDITOR=mg
export METAMAIL_PAGER=less
export CONCURRENCY_LEVEL="2"
export DEBEMAIL="frank@carmickle.com"
export SSL_CERT_DIR=/etc/ssl/certs
export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt

EOF

cat <<EOF > "${WORK_DIR}/root/.bashrc"
# ~/.bashrc: executed by bash(1) for non-login shells.
HISTCONTROL=ignoreboth
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize

[ -x /usr/bin/lesspipe ] && eval "\$(SHELL=/bin/sh lesspipe)"

if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

alias jac='journalctl -o cat --no-pager --no-hostname | less'
alias emacs='/usr/bin/mg '
alias ls='ls -1F '
alias day='/bin/date +%Y%m%d -u '
alias mem='ps --sort -rss -eo rss,pid,tty,command | head '
alias datetime='/bin/date +%Y%m%d%k%M -u'
export LESS="-CiMR~X"
export VISUAL=mg
export EDITOR=mg
export METAMAIL_PAGER=less
export CONCURRENCY_LEVEL="2"
export DEBEMAIL="frank@carmickle.com"
export SSL_CERT_DIR=/etc/ssl/certs/
export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt

EOF

cat <<EOF > "${WORK_DIR}/home/frankiec/.tmux.conf"
set -g default-terminal screen
set-option -g status off
set -g history-limit 100000
set -g visual-activity off
setw -g monitor-activity on
set -g alternate-screen off

bind -n F1  select-window -t :1
bind -n F2  select-window -t :2
bind -n F3  select-window -t :3
bind -n F4  select-window -t :4
bind -n F5  select-window -t :5
bind -n F6  select-window -t :6
bind -n F7  select-window -t :7
bind -n F8  select-window -t :8
bind -n F9  select-window -t :9
bind -n F10 select-window -t :10
bind -n F11 select-window -t :11
bind -n F12 select-window -t :12

new
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad
neww -ad

EOF

sed 's/^.*PasswordAuthentication yes$/PasswordAuthentication no/' -i "${WORK_DIR}/etc/ssh/sshd_config"

cat <<EOF >> "${WORK_DIR}/etc/ssh/sshd_config"
LogLevel ERROR
LoginGraceTime 1m
MaxAuthTries 2
MaxSessions 12

HostKeyAlgorithms ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519,sk-ssh-ed25519@openssh.com
ciphers chacha20-poly1305@openssh.com
macs umac-64-etm@openssh.com,umac-128-etm@openssh.com
kexalgorithms curve25519-sha256,curve25519-sha256@libssh.org
casignaturealgorithms ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,ssh-ed25519,sk-ssh-ed25519@openssh.com,rsa-sha2-512,rsa-sha2-256
hostbasedacceptedkeytypes ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519,sk-ssh-ed25519@openssh.com
pubkeyacceptedkeytypes ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519,sk-ssh-ed25519@openssh.com

EOF

echo "${DATETIME}" > "${WORK_DIR}/etc/build_date"

sed 's/Defaults.*env_reset$/Defaults    env_keep += "LANGUAGE VISUAL EDITOR METAMAIL_PAGER LESS HOME",timestamp_timeout=2,!tty_tickets/' -i "${WORK_DIR}/etc/sudoers"
sed 's/^%sudo.*$/%sudo ALL=(ALL:ALL) NOPASSWD: ALL/' -i "${WORK_DIR}/etc/sudoers"

cat <<EOF > "${WORK_DIR}/usr/local/sbin/wg-init-key"
#!/bin/bash

if [ -s /etc/wireguard/wg0.key ]; then
    echo "wg0 private key already exists, skipping."
    exit 0
fi

umask 037
mkdir -p /etc/wireguard
wg genkey | tee /etc/wireguard/wg0.key | wg pubkey > /etc/wireguard/wg0.key.pub
chown -R root:systemd-network /etc/wireguard
chmod g+x /etc/wireguard
sleep 1

EOF

cat <<EOF > "${WORK_DIR}/etc/systemd/system/wg-init-key.service"
[Unit]
Before=systemd-networkd.service

[Install]
RequiredBy=systemd-networkd.service

[Service]
Type=oneshot
ExecStart=/bin/bash /usr/local/sbin/wg-init-key

EOF

# wg-publish-pubkey and its base unit are owned by the routedvpn.com
# wg-oewg package. The image only adds ordering against its local key
# generator; package updates can replace the implementation independently.
install -d -m 0755 \
  "${WORK_DIR}/etc/systemd/system/wg-publish-pubkey.service.d"
cat <<EOF > "${WORK_DIR}/etc/systemd/system/wg-publish-pubkey.service.d/10-mkrootfs.conf"
[Unit]
After=wg-init-key.service
Requires=wg-init-key.service
EOF

cat <<EOF > "${WORK_DIR}/usr/local/sbin/snapupdate"
#!/bin/bash

apt-get autoclean
apt-get autoremove -y
btrfs sub snap / /snaps/$(/bin/date +%Y%m%d%H%M -u)
apt-get update
apt-get dist-upgrade -Vuy

EOF

cp -a "${FUNCTION_DIR}/firstboot" "${WORK_DIR}/usr/local/sbin/firstboot"

cat <<EOF > "${WORK_DIR}/etc/systemd/system/firstboot.service"
[Unit]
Description=First-boot rootfs resize and PTR-driven hostname discovery
ConditionPathExists=!/var/lib/firstboot.done
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/firstboot
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

chmod 750 "${WORK_DIR}/usr/local/sbin/"*
chroot "${WORK_DIR}" systemctl enable firstboot.service
chroot "${WORK_DIR}" systemctl enable wg-init-key.service
chroot "${WORK_DIR}" systemctl enable wg-publish-pubkey.service

[ -f "${WORK_DIR}/etc/apt/apt.conf.d/99mmdebstrap" ] && sed 's/^Acquire::.*$//' -i "${WORK_DIR}/etc/apt/apt.conf.d/99mmdebstrap"
for BINDMOUNT in dev proc sys dev/pts; do
    mount -o bind "/${BINDMOUNT}" "/mnt/rootfs/${BINDMOUNT}"
done

chroot /mnt/rootfs update-grub

for BTRPART in $(btrfs filesystem show "$(findfs rootfs)" | grep devid | awk '{ print $NF }'); do
    SSD="$(lsblk -nro PKNAME "${BTRPART}")"
    chroot /mnt/rootfs grub-install "/dev/${SSD}"
done
