#!/usr/bin/env bash

public_key="/opt/rustdesk/id_ed25519.pub"
private_key="/opt/rustdesk/id_ed25519"

function genNewKeys() {
	echo "Generatiing a new key pair"
	KEY_PAIR=$(/opt/rustdesk/rustdesk-utils genkeypair )
	PUBLIC_KEY=$(echo "${KEY_PAIR}"|head -1 |awk '{print $3}')
	PRIVATE_KEY=$(echo "${KEY_PAIR}"|tail -1 |awk '{print $3}')
	echo -n "${PUBLIC_KEY}" > "${public_key}"
	echo -n "${PRIVATE_KEY}" > "${private_key}"
}

function validateNewKeys() {
        PUBLIC_KEY=$(cat "${public_key}" 2>/dev/null)
	PRIVATE_KEY=$(cat "${private_key}" 2>/dev/null )
	/opt/rustdesk/rustdesk-utils validatekeypair "${PUBLIC_KEY}" "${PRIVATE_KEY}"
}

stat "${public_key}" >/dev/null 2>&1
stat "${private_key}" >/dev/null 2>&1

valid_key_pair="0"

while [[ "$valid_key_pair" != "1" ]]; do
	validateNewKeys | grep "^Key pair is VALID" >/dev/null
	if [ "$?" -eq "0" ];then
		echo "Foudn the keys to be VALID"
		valid_key_pair="1"
	else
		echo "Found the keys to be invalid"
		valid_key_pair="0"
		genNewKeys
	fi

done
