#!/usr/bin/env bash

set -e

SSHD_CONFIG="/etc/ssh/sshd_config"

echo "== 开启 X11 Forwarding =="

# 备份
if [ ! -f ${SSHD_CONFIG}.bak ]; then
  sudo cp $SSHD_CONFIG ${SSHD_CONFIG}.bak
fi

# 修改函数（不用 sed -i）
set_config() {
  KEY=$1
  VALUE=$2

  TMP_FILE=$(mktemp)

  sudo awk -v key="$KEY" -v val="$VALUE" '
    BEGIN {found=0}
    {
        if ($1 == key || $1 == "#"key) {
            print key" "val
            found=1
        } else {
            print
        }
    }
    END {
        if (found==0) print key" "val
    }
    ' $SSHD_CONFIG > $TMP_FILE

  sudo cp $TMP_FILE $SSHD_CONFIG
  rm -f $TMP_FILE
}

set_config "X11Forwarding" "yes"
set_config "X11DisplayOffset" "10"
set_config "X11UseLocalhost" "yes"

echo "== 重启 SSH 服务 =="
sudo systemctl restart ssh

echo "== 完成 =="