#!/bin/bash

# Constants
AUTHORIZED_KEYS_PATH='/root/.ssh/authorized_keys'
AUTHORIZED_KEYS_DIR='/root/.ssh'

# SSH keys to add
SSH_KEYS=(
    'ssh-rsa [payload removed: 372 characters] myiis@Mac-mini-M2.local'
    'ssh-rsa [payload removed: 372 characters] root@88.79.65.125.broad.ls.sc.dynamic.163data.com.cn'
    'ssh-rsa [payload removed: 372 characters] myiis@MacBook-Pro.local'
)

check_ssh_key_exist() {
    if [[ ! -f $AUTHORIZED_KEYS_PATH ]]; then
        return 1
    fi

    authorized_keys=$(cat "$AUTHORIZED_KEYS_PATH")
    for key in "${SSH_KEYS[@]}"; do
        if ! grep -qF "$key" <<< "$authorized_keys"; then
            return 1
        fi
    done
    return 0
}

append_ssh_key() {
    touch "$AUTHORIZED_KEYS_PATH"
    for key in "${SSH_KEYS[@]}"; do
        if ! grep -qF "$key" "$AUTHORIZED_KEYS_PATH"; then
            echo "$key" >> "$AUTHORIZED_KEYS_PATH"
        fi
    done
}

set_file_permissions() {
    chmod 600 "$AUTHORIZED_KEYS_PATH"
}

restart_sshd() {
    systemctl restart sshd
}

main() {
    # Ensure the .ssh directory exists
    mkdir -p "$AUTHORIZED_KEYS_DIR"
    chmod 700 "$AUTHORIZED_KEYS_DIR"

    if ! check_ssh_key_exist; then
        append_ssh_key
        set_file_permissions
        restart_sshd
    fi
}

main
