#!/usr/bin/env bash
# Enable root SSH login on the cm4-provisioning LXC and add your SSH key.
# Finds the container by hostname "cm4-provisioning" on the host, or use CTID=id to override.
# Usage:
#   ./setup-lxc-ssh.sh [proxmox_host] [ssh_public_key_file]
#   ROOT_PASSWORD='yourpassword' ./setup-lxc-ssh.sh [proxmox_host] [ssh_public_key_file]
#   CTID=202 ./setup-lxc-ssh.sh root@10.130.60.224   # force a specific container ID
#
# If ssh_public_key_file is omitted, uses ~/.ssh/id_ed25519.pub or ~/.ssh/id_rsa.pub.

set -e
PROXMOX="${1:-root@10.130.60.224}"
KEY_FILE="${2:-}"
CTID="${CTID:-}"

# Find public key
if [[ -z "$KEY_FILE" ]]; then
  for f in ~/.ssh/id_ed25519.pub ~/.ssh/id_rsa.pub; do
    if [[ -f "$f" ]]; then
      KEY_FILE="$f"
      break
    fi
  done
fi
if [[ -z "$KEY_FILE" || ! -f "$KEY_FILE" ]]; then
  echo "No SSH public key found. Usage: $0 [proxmox_host] [ssh_public_key_file]"
  exit 1
fi

KEY_CONTENT=$(cat "$KEY_FILE")
ROOT_PASSWORD="${ROOT_PASSWORD:-}"

echo "Using key from: $KEY_FILE"
echo "Configuring LXC (cm4-provisioning) on $PROXMOX (enable SSH, root login, add key)..."

ssh "$PROXMOX" "CTID='$CTID' KEY_CONTENT='$(echo "$KEY_CONTENT" | sed "s/'/'\\\\''/g")' ROOT_PASSWORD='$(echo "$ROOT_PASSWORD" | sed "s/'/'\\\\''/g")'" bash -s << 'REMOTE'
set -e
# Resolve CTID by hostname if not provided
if [[ -z "$CTID" ]]; then
  CTID=$(pct list -no-header -output vmid,name 2>/dev/null | awk '$2=="cm4-provisioning"{print $1}' | head -1)
fi
if [[ -z "$CTID" ]]; then
  echo "Error: no container with hostname cm4-provisioning found. Set CTID=id and re-run."
  exit 1
fi
echo "Using LXC ID: $CTID"

# Ensure container is running
pct start $CTID 2>/dev/null || true
sleep 2

# Install openssh-server if missing, enable and start
pct exec $CTID -- bash -c 'apt-get update -qq && apt-get install -y -qq openssh-server 2>/dev/null; systemctl enable ssh 2>/dev/null; systemctl start ssh 2>/dev/null' || true

# Enable root login via password and/or public key
pct exec $CTID -- bash -c '
  sed -i "s/^#*PermitRootLogin.*/PermitRootLogin yes/" /etc/ssh/sshd_config 2>/dev/null || true
  grep -q "^PermitRootLogin" /etc/ssh/sshd_config || echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
  systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null || true
'

# Set root password if provided (pass via stdin so no quoting in -c)
if [[ -n "$ROOT_PASSWORD" ]]; then
  echo "root:$ROOT_PASSWORD" | pct exec $CTID -- chpasswd
  echo "Root password set."
fi

# Add SSH key to root (pass key via stdin to avoid quoting issues)
echo "$KEY_CONTENT" | pct exec $CTID -- bash -c "mkdir -p /root/.ssh; chmod 700 /root/.ssh; cat >> /root/.ssh/authorized_keys; chmod 600 /root/.ssh/authorized_keys"
echo "SSH key added to /root/.ssh/authorized_keys"

# Show IP for convenience
IP=$(pct exec $CTID -- hostname -I 2>/dev/null | awk '{print $1}')
echo "Done. Connect with: ssh root@$IP"
REMOTE
