#!/bin/bash
set -e

# Generate SSH host keys if not present
ssh-keygen -A

# Write authorized keys from env if provided
if [ -n "$SSH_AUTHORIZED_KEYS" ]; then
  mkdir -p /root/.ssh
  chmod 700 /root/.ssh
  echo "$SSH_AUTHORIZED_KEYS" > /root/.ssh/authorized_keys
  chmod 600 /root/.ssh/authorized_keys
fi

# Bootstrap home dir on fresh PVC
if [ ! -f /root/.bashrc ]; then
  cp /etc/skel/.bashrc /root/.bashrc 2>/dev/null || true
  cat >> /root/.bashrc <<'EOF'
export PATH="/usr/local/bin:$PATH"
export HISTFILE=/root/.bash_history
export HISTSIZE=10000
EOF
fi

if [ ! -f /root/.profile ]; then
  cat > /root/.profile <<'EOF'
export PATH="/usr/local/bin:$PATH"
[ -f /root/.bashrc ] && . /root/.bashrc
EOF
fi

if [ ! -f /root/.gitconfig ]; then
  cat > /root/.gitconfig <<'EOF'
[user]
  name = ryan
  email = ryan@lunartech.com
[init]
  defaultBranch = main
[core]
  editor = code --wait
EOF
fi

# Install Claude Code on first boot (installs to /root/.claude, persists on PVC)
if [ ! -f /root/.claude/bin/claude ]; then
  curl -fsSL https://claude.ai/install.sh | bash
fi

# Allow root login via SSH key, listen on internal port 2222
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
echo "Port 2222" >> /etc/ssh/sshd_config

# Start SSH daemon on internal port 2222
/usr/sbin/sshd

# Start haproxy on port 22 to accept PROXY protocol from nginx and forward to sshd:2222
cat > /etc/haproxy/haproxy.cfg <<'EOF'
global
  daemon
  maxconn 256

defaults
  mode tcp
  timeout connect 5s
  timeout client  60s
  timeout server  60s

frontend ssh
  bind *:22 accept-proxy
  default_backend sshd

backend sshd
  server local 127.0.0.1:2222
EOF
haproxy -f /etc/haproxy/haproxy.cfg

# Start code-server
exec code-server \
  --bind-addr 0.0.0.0:8080 \
  --auth none \
  --disable-telemetry \
  /root
