#!/bin/bash
# CDM Linux Post-Install Script
# Runs inside arch-chroot during archinstall custom-commands
set -e

echo "=== CDM Linux Post-Install ==="

# --- Shell ---
echo "[..] Setting zsh as default shell for cdm..."
chsh -s /usr/bin/zsh cdm

# --- SSH Key ---
echo "[..] Deploying SSH key..."
mkdir -p /home/cdm/.ssh
cat > /home/cdm/.ssh/authorized_keys << 'KEY'
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPuZIJoHsVdrJ0p3/Fp613MhEsUYRxIZ5tYt1RnRdekr explify@gmail.com
KEY
chmod 700 /home/cdm/.ssh
chmod 600 /home/cdm/.ssh/authorized_keys
chown -R cdm:cdm /home/cdm/.ssh

# --- Passwordless sudo ---
echo "[..] Configuring passwordless sudo for cdm..."
echo "cdm ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/cdm
chmod 440 /etc/sudoers.d/cdm

# --- Create installers group ---
groupadd -f installers

# --- Tailscale auto-join on first boot ---
echo "[..] Setting up Tailscale auto-join..."
cat > /etc/systemd/system/tailscale-autoconnect.service << 'EOF'
[Unit]
Description=Auto-connect to CDM Tailscale network
After=tailscaled.service network-online.target
Wants=tailscaled.service network-online.target
ConditionPathExists=!/etc/tailscale-joined

[Service]
Type=oneshot
ExecStartPre=/usr/bin/sleep 5
ExecStart=/usr/bin/tailscale up --auth-key=tskey-auth-kpUBzRpjSR11CNTRL-Toy3t9tvc4bih2QaTMr55bG7aSBbetPCb
ExecStartPost=/usr/bin/touch /etc/tailscale-joined
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF
systemctl enable tailscale-autoconnect

# --- Mirrors ---
echo "[..] Setting fastest Russian mirrors..."
reflector --country Russia --age 12 --protocol https --sort rate --save /etc/pacman.d/mirrorlist 2>/dev/null || true

# --- Journal size limit ---
mkdir -p /etc/systemd/journald.conf.d
cat > /etc/systemd/journald.conf.d/size-limit.conf << 'EOF'
[Journal]
SystemMaxUse=500M
EOF

# --- UFW basic rules ---
echo "[..] Configuring firewall..."
ufw default deny incoming
ufw default allow outgoing
ufw allow from 100.64.0.0/10 to any port 22 comment "Tailscale SSH"
ufw --force enable

# --- Generate both locales ---
echo "[..] Generating locales..."
sed -i 's/^#en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
sed -i 's/^#ru_RU.UTF-8/ru_RU.UTF-8/' /etc/locale.gen
locale-gen

echo "=== CDM Linux Post-Install Complete ==="
