Index: /branches/rel_apv_10_7/usr/click/bin/backend/ntp.c
===================================================================
--- /branches/rel_apv_10_7/usr/click/bin/backend/ntp.c	(revision 40279)
+++ /branches/rel_apv_10_7/usr/click/bin/backend/ntp.c	(working copy)
@@ -356,6 +356,32 @@
     return 0;
 }
 
+int is_ntp_key_exist(int key_id) {
+    FILE *fp = NULL;
+    int id;
+    char type[10], value[NTP_MAX_AUTH_KEY_LEN];
+    char line[256];
+
+    fp = fopen(CHRONY_KEYS_FILE, "r");
+    if (!fp) {
+        printf("Failed to open chrony keys file\n");
+        return 0;
+    }
+
+    while (fgets(line, sizeof(line), fp)) {
+        if (line[0] == '#' || line[0] == '\n')
+            continue;
+        if (sscanf(line, "%d %s %s", &id, type, value) == 3) {
+            if (id == key_id) {
+                fclose(fp);
+                return 1;
+            }
+        }
+    }
+    fclose(fp);
+    return 0;
+}
+
 int ui_ntpserver(char *host, char *option, int key_id) 
 {
     char srv_config[1024] = {0}, cmd[1024], delete_cmd[1024], copy[256] = {0};
@@ -397,11 +423,22 @@
         snprintf(srv_config, sizeof(srv_config), "server %s %s", host, option);
     }
 
+    if (key_id == 0) {
+        // The key is default 0. However, 0 is not in valid range.
+        printf("The Key ID is mandatory for NTP server\n");
+        return -1;
+    }
+
     /* Key Validation */
     if (key_id < NTP_MIN_AUTH_KEY_ID || key_id > NTP_MAX_AUTH_KEY_ID) {
-         return -1;
-    } 
-    
+        return -1;
+    }
+
+    if (!is_ntp_key_exist(key_id)) {
+        printf("The Key ID %d does not exist, please add the key first\n", key_id);
+        return -1;
+    }
+
     /* Append the key if key_id is provided */
     if(key_id) {
         snprintf(srv_config + strlen(srv_config), sizeof(srv_config) - strlen(srv_config), " key %d", key_id);
@@ -495,8 +532,43 @@
     return 0;
 }
 
+int is_key_bound_to_server(int key_id) {
+    FILE *fp = NULL;
+    char line[512];
+    char *p;
+    int found = 0;
+
+    fp = fopen(CHRONY_CONF_FILE, "r");
+    if (!fp) {
+        printf("Failed to open chrony conf file\n");
+        return 0;
+    }
+
+    while (fgets(line, sizeof(line), fp)) {
+        if (strncmp(line, "server", 6) == 0) {
+            char *key_ptr = strstr(line, "key ");
+            if (key_ptr) {
+                int id = 0;
+                if (sscanf(key_ptr, "key %d", &id) == 1) {
+                    if (id == key_id) {
+                        found = 1;
+                        break;
+                    }
+                }
+            }
+        }
+    }
+    fclose(fp);
+    return found;
+}
+
 int ui_no_ntp_auth_key(int key_id)
 {
+    if (is_key_bound_to_server(key_id)) {
+        printf("The Key ID %d is still bound to an NTP server, please remove the server first\n", key_id);
+        return -1;
+    }
+
     if(!delete_ntpkey_conf(key_id)) {
         printf("NTP authentication key not found\n");
         return 1;
