-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPowerTimer.c
More file actions
629 lines (537 loc) · 15.4 KB
/
PowerTimer.c
File metadata and controls
629 lines (537 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/*
* PowerTimer - Programador de Apagado/Reinicio
* Compilar: gcc PowerTimer.c -o PowerTimer.exe
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <conio.h>
#define MAX_PATH_LEN 512
#define MAX_LINE_LEN 256
#define LOG_TAIL_LINES 200
// Colores para la consola
#define COLOR_DEFAULT 0x0A // Verde sobre negro
#define COLOR_ERROR 0x0C // Rojo
#define COLOR_WARNING 0x0E // Amarillo
#define COLOR_INFO 0x0B // Cyan
typedef struct
{
char action[16];
int minutes;
int seconds;
char requested_at[32];
char target_at[32];
char user[64];
char pc[64];
} PendingState;
// Rutas globales
char g_script_dir[MAX_PATH_LEN];
char g_log_path[MAX_PATH_LEN];
char g_state_path[MAX_PATH_LEN];
char g_username[64];
char g_computername[64];
// Prototipos
void init_paths(void);
void set_console_color(WORD color);
void clear_screen(void);
void print_banner(void);
void print_menu(void);
void show_pending(void);
int load_pending_state(PendingState *state);
void save_pending_state(const PendingState *state);
void delete_pending_state(void);
void get_timestamp(char *buffer, size_t size);
void get_future_timestamp(char *buffer, size_t size, int minutes);
void log_event(const char *format, ...);
void schedule_action(const char *action);
void cancel_schedule(void);
void view_history(void);
void open_log(void);
void clear_history(void);
int ask_minutes(void);
void startup_check(void);
void wait_key(void);
int run_shutdown_cmd(const char *args);
int main(void)
{
SetConsoleTitle("PowerTimer - Programador de Apagado/Reinicio");
SetConsoleOutputCP(CP_UTF8);
init_paths();
set_console_color(COLOR_DEFAULT);
// Verificar si hay programación pendiente al iniciar
startup_check();
int running = 1;
while (running)
{
clear_screen();
print_banner();
show_pending();
print_menu();
printf("\nElige una opcion: ");
int opt = _getch();
printf("%c\n", opt);
switch (opt)
{
case '1':
schedule_action("SHUTDOWN");
break;
case '2':
schedule_action("RESTART");
break;
case '3':
cancel_schedule();
break;
case '4':
view_history();
break;
case '5':
open_log();
break;
case '6':
clear_history();
break;
case '0':
case 27: // ESC
running = 0;
break;
default:
set_console_color(COLOR_ERROR);
printf("\nOpcion no valida.\n");
set_console_color(COLOR_DEFAULT);
Sleep(1500);
break;
}
}
return 0;
}
void init_paths(void)
{
// Obtener directorio del ejecutable
GetModuleFileName(NULL, g_script_dir, MAX_PATH_LEN);
char *last_slash = strrchr(g_script_dir, '\\');
if (last_slash)
*last_slash = '\0';
snprintf(g_log_path, MAX_PATH_LEN, "%s\\PowerTimer.log", g_script_dir);
snprintf(g_state_path, MAX_PATH_LEN, "%s\\PowerTimer.pending", g_script_dir);
// Obtener usuario y nombre de PC
DWORD size = sizeof(g_username);
GetUserName(g_username, &size);
size = sizeof(g_computername);
GetComputerName(g_computername, &size);
}
void set_console_color(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void clear_screen(void)
{
system("cls");
}
void print_banner(void)
{
printf("=========================================================\n");
printf(" PowerTimer (C)\n");
printf(" Programar Apagado / Reinicio + Historial\n");
printf(" Log: %s\n", g_log_path);
printf("=========================================================\n\n");
}
void print_menu(void)
{
printf("\n[1] Programar APAGADO\n");
printf("[2] Programar REINICIO\n");
printf("[3] Cancelar programacion actual\n");
printf("[4] Ver historial (ultimas %d lineas)\n", LOG_TAIL_LINES);
printf("[5] Abrir LOG en editor\n");
printf("[6] Borrar historial\n");
printf("[0] Salir\n");
}
void show_pending(void)
{
PendingState state;
if (load_pending_state(&state))
{
set_console_color(COLOR_WARNING);
printf("Pendiente: %s en %d min | solicitado: %s | programado: %s\n",
state.action, state.minutes, state.requested_at, state.target_at);
set_console_color(COLOR_DEFAULT);
}
else
{
printf("Pendiente: (nada programado)\n");
}
}
int load_pending_state(PendingState *state)
{
FILE *f = fopen(g_state_path, "r");
if (!f)
return 0;
memset(state, 0, sizeof(PendingState));
char line[MAX_LINE_LEN];
while (fgets(line, sizeof(line), f))
{
line[strcspn(line, "\r\n")] = 0;
char *eq = strchr(line, '=');
if (!eq)
continue;
*eq = '\0';
char *key = line;
char *val = eq + 1;
if (strcmp(key, "ACTION") == 0)
strncpy(state->action, val, sizeof(state->action) - 1);
else if (strcmp(key, "MINUTES") == 0)
state->minutes = atoi(val);
else if (strcmp(key, "SECONDS") == 0)
state->seconds = atoi(val);
else if (strcmp(key, "REQUESTED_AT") == 0)
strncpy(state->requested_at, val, sizeof(state->requested_at) - 1);
else if (strcmp(key, "TARGET_AT") == 0)
strncpy(state->target_at, val, sizeof(state->target_at) - 1);
else if (strcmp(key, "USER") == 0)
strncpy(state->user, val, sizeof(state->user) - 1);
else if (strcmp(key, "PC") == 0)
strncpy(state->pc, val, sizeof(state->pc) - 1);
}
fclose(f);
return strlen(state->action) > 0;
}
void save_pending_state(const PendingState *state)
{
FILE *f = fopen(g_state_path, "w");
if (!f)
{
set_console_color(COLOR_ERROR);
printf("Error: No se pudo guardar el estado.\n");
set_console_color(COLOR_DEFAULT);
return;
}
fprintf(f, "ACTION=%s\n", state->action);
fprintf(f, "MINUTES=%d\n", state->minutes);
fprintf(f, "SECONDS=%d\n", state->seconds);
fprintf(f, "REQUESTED_AT=%s\n", state->requested_at);
fprintf(f, "TARGET_AT=%s\n", state->target_at);
fprintf(f, "USER=%s\n", g_username);
fprintf(f, "PC=%s\n", g_computername);
fclose(f);
}
void delete_pending_state(void)
{
DeleteFile(g_state_path);
}
void get_timestamp(char *buffer, size_t size)
{
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
strftime(buffer, size, "%Y-%m-%d %H:%M:%S", tm_info);
}
void get_future_timestamp(char *buffer, size_t size, int minutes)
{
time_t future = time(NULL) + (minutes * 60);
struct tm *tm_info = localtime(&future);
strftime(buffer, size, "%Y-%m-%d %H:%M:%S", tm_info);
}
void log_event(const char *format, ...)
{
FILE *f = fopen(g_log_path, "a");
if (!f)
return;
char timestamp[32];
get_timestamp(timestamp, sizeof(timestamp));
fprintf(f, "[%s] ", timestamp);
va_list args;
va_start(args, format);
vfprintf(f, format, args);
va_end(args);
fprintf(f, "\n");
fclose(f);
}
void schedule_action(const char *action)
{
clear_screen();
print_banner();
printf("Vas a programar: %s\n\n", action);
// Si ya hay algo programado, cancelarlo primero
PendingState old_state;
if (load_pending_state(&old_state))
{
// Cancelar el anterior
run_shutdown_cmd("/a");
log_event("AUTO_CANCEL prev_action=%s prev_minutes=%d prev_target=%s user=%s pc=%s",
old_state.action, old_state.minutes, old_state.target_at, g_username, g_computername);
delete_pending_state();
}
int minutes = ask_minutes();
if (minutes <= 0)
return;
int seconds = minutes * 60;
PendingState state;
strncpy(state.action, action, sizeof(state.action) - 1);
state.minutes = minutes;
state.seconds = seconds;
get_timestamp(state.requested_at, sizeof(state.requested_at));
get_future_timestamp(state.target_at, sizeof(state.target_at), minutes);
save_pending_state(&state);
log_event("SCHEDULE action=%s minutes=%d target=%s seconds=%d user=%s pc=%s",
action, minutes, state.target_at, seconds, g_username, g_computername);
// Ejecutar shutdown
char args[256];
if (strcmp(action, "SHUTDOWN") == 0)
{
snprintf(args, sizeof(args), "/s /t %d /c \"PowerTimer: apagado programado en %d minutos.\"", seconds, minutes);
}
else
{
snprintf(args, sizeof(args), "/r /t %d /c \"PowerTimer: reinicio programado en %d minutos.\"", seconds, minutes);
}
int result = run_shutdown_cmd(args);
if (result == 0)
{
set_console_color(COLOR_INFO);
printf("\nProgramado: %s en %d minutos.\n", action, minutes);
printf("Hora programada (aprox): %s\n", state.target_at);
set_console_color(COLOR_DEFAULT);
}
else
{
set_console_color(COLOR_ERROR);
printf("\nError al programar el %s.\n", action);
set_console_color(COLOR_DEFAULT);
delete_pending_state();
}
wait_key();
}
int ask_minutes(void)
{
char input[32];
int minutes;
while (1)
{
printf("Introduce minutos (1 - 525600, 0 para cancelar): ");
if (!fgets(input, sizeof(input), stdin))
return 0;
input[strcspn(input, "\r\n")] = 0;
if (strlen(input) == 0)
{
set_console_color(COLOR_ERROR);
printf("Debes escribir un numero.\n");
set_console_color(COLOR_DEFAULT);
continue;
}
// Verificar que solo contiene dígitos
int valid = 1;
for (int i = 0; input[i]; i++)
{
if (input[i] < '0' || input[i] > '9')
{
valid = 0;
break;
}
}
if (!valid)
{
set_console_color(COLOR_ERROR);
printf("Solo numeros, por favor.\n");
set_console_color(COLOR_DEFAULT);
continue;
}
minutes = atoi(input);
if (minutes == 0)
return 0;
if (minutes < 1)
{
set_console_color(COLOR_ERROR);
printf("Debe ser mayor o igual a 1.\n");
set_console_color(COLOR_DEFAULT);
continue;
}
if (minutes > 525600)
{
set_console_color(COLOR_ERROR);
printf("Maximo 525600 (1 ano).\n");
set_console_color(COLOR_DEFAULT);
continue;
}
return minutes;
}
}
void cancel_schedule(void)
{
clear_screen();
print_banner();
printf("\n");
PendingState state;
int had_state = load_pending_state(&state);
printf("Cancelando programacion...\n\n");
fflush(stdout);
int result = run_shutdown_cmd("/a");
int success = (result == 0);
if (success)
{
set_console_color(COLOR_INFO);
printf("Cancelado correctamente.\n");
set_console_color(COLOR_DEFAULT);
if (had_state)
{
log_event("CANCEL result=OK prev_action=%s prev_minutes=%d prev_requested=%s prev_target=%s user=%s pc=%s",
state.action, state.minutes, state.requested_at, state.target_at, g_username, g_computername);
}
else
{
log_event("CANCEL result=OK user=%s pc=%s", g_username, g_computername);
}
delete_pending_state();
}
else
{
set_console_color(COLOR_WARNING);
printf("No habia ningun apagado/reinicio programado (o no se pudo cancelar).\n");
set_console_color(COLOR_DEFAULT);
log_event("CANCEL result=NO_PENDING user=%s pc=%s", g_username, g_computername);
if (had_state)
{
delete_pending_state();
}
}
printf("\n");
fflush(stdout);
wait_key();
}
void view_history(void)
{
clear_screen();
print_banner();
FILE *f = fopen(g_log_path, "r");
if (!f)
{
printf("No hay historial todavia.\n");
wait_key();
return;
}
// Contar líneas
int total_lines = 0;
char line[MAX_LINE_LEN];
while (fgets(line, sizeof(line), f))
total_lines++;
// Volver al inicio y saltar las primeras líneas si hay más de LOG_TAIL_LINES
rewind(f);
int skip = (total_lines > LOG_TAIL_LINES) ? (total_lines - LOG_TAIL_LINES) : 0;
for (int i = 0; i < skip; i++)
{
fgets(line, sizeof(line), f);
}
// Mostrar las últimas líneas
while (fgets(line, sizeof(line), f))
{
printf("%s", line);
}
fclose(f);
printf("\n");
wait_key();
}
void open_log(void)
{
// Crear el log si no existe
FILE *f = fopen(g_log_path, "a");
if (f)
{
fclose(f);
}
// Verificar si VS Code está disponible
char code_path[MAX_PATH_LEN];
DWORD result = SearchPath(NULL, "code.cmd", NULL, MAX_PATH_LEN, code_path, NULL);
if (result > 0)
{
// Abrir con VS Code
ShellExecute(NULL, "open", "code", g_log_path, NULL, SW_SHOWNORMAL);
}
else
{
// Abrir con Notepad
ShellExecute(NULL, "open", "notepad.exe", g_log_path, NULL, SW_SHOWNORMAL);
}
}
void clear_history(void)
{
clear_screen();
print_banner();
printf("Seguro que quieres BORRAR el historial? (S/N): ");
int c = _getch();
printf("%c\n", c);
if (c == 's' || c == 'S' || c == 'y' || c == 'Y')
{
if (DeleteFile(g_log_path))
{
set_console_color(COLOR_INFO);
printf("Historial borrado.\n");
set_console_color(COLOR_DEFAULT);
}
else
{
DWORD err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND)
{
printf("No habia historial.\n");
}
else
{
set_console_color(COLOR_ERROR);
printf("Error al borrar el historial.\n");
set_console_color(COLOR_DEFAULT);
}
}
}
else
{
printf("Cancelado.\n");
}
Sleep(1500);
}
void startup_check(void)
{
PendingState state;
if (!load_pending_state(&state))
return;
clear_screen();
print_banner();
show_pending();
printf("\nHay una programacion pendiente. Cancelar ahora? (S/N): ");
int c = _getch();
printf("%c\n", c);
if (c == 's' || c == 'S' || c == 'y' || c == 'Y')
{
cancel_schedule();
}
}
void wait_key(void)
{
printf("\nPresiona cualquier tecla para continuar...");
_getch();
}
// Ejecuta un comando shutdown sin afectar la consola actual
// Retorna 0 si exitoso, otro valor si falla
int run_shutdown_cmd(const char *args)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
char cmd[512];
snprintf(cmd, sizeof(cmd), "C:\\Windows\\System32\\shutdown.exe %s", args);
int result = 1;
if (CreateProcess(NULL, cmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
WaitForSingleObject(pi.hProcess, 5000);
DWORD exitCode = 1;
GetExitCodeProcess(pi.hProcess, &exitCode);
result = (int)exitCode;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
// Restaurar título de consola por si acaso
SetConsoleTitle("PowerTimer - Programador de Apagado/Reinicio");
return result;
}