Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

41.5 KB
Raw Blame
import { EventEmitter } from 'events';
import { PassThrough, Writable } from 'stream';

// Mock modules BEFORE importing the function under test
jest.mock('child_process');
jest.mock('../../../src/utils/binaryPathResolver');
jest.mock('../../../src/utils/rclone/helpers');
jest.mock('../../../src/utils/AppPaths', () => ({
	appPaths: {
		getConfigDir: jest.fn().mockReturnValue('/mock/config'),
		getTempDir: jest.fn().mockReturnValue('/mock/temp'),
	},
}));
jest.mock('../../../src/utils/restic/helpers');
jest.mock('../../../src/utils/processTree', () => ({
	killProcessTree: jest.fn(),
}));
jest.mock('../../../src/services/ConfigService', () => ({
	configService: {
		config: {
			ENCRYPTION_KEY: 'test-encryption-key',
		},
		isSetupPending: jest.fn().mockReturnValue(false),
	},
}));

import { spawn } from 'child_process';
import {
	runResticCommand,
	getBackupPlanStats,
	getSnapshotByTag,
	getSnapshotsByTag,
	handleResticCheckResult,
} from '../../../src/utils/restic/restic';
import { getBinaryPath } from '../../../src/utils/binaryPathResolver';
import { getRcloneConfigPath } from '../../../src/utils/rclone/helpers';
import { appPaths } from '../../../src/utils/AppPaths';
import { generateResticRepoPath } from '../../../src/utils/restic/helpers';
import { killProcessTree } from '../../../src/utils/processTree';

const mockSpawn = spawn as jest.MockedFunction<typeof spawn>;
const mockKillProcessTree = killProcessTree as jest.MockedFunction<typeof killProcessTree>;
const mockGetBinaryPath = getBinaryPath as jest.MockedFunction<typeof getBinaryPath>;
const mockGetRcloneConfigPath = getRcloneConfigPath as jest.MockedFunction<
	typeof getRcloneConfigPath
>;
const mockAppPaths = appPaths as jest.Mocked<typeof appPaths>;
const mockGenerateResticRepoPath = generateResticRepoPath as jest.MockedFunction<
	typeof generateResticRepoPath
>;

describe('runResticCommand', () => {
	let mockProcess: any;

	beforeEach(() => {
		jest.clearAllMocks();

		// Setup default mock implementations
		mockGetBinaryPath.mockImplementation((binary: string) => `/mock/path/${binary}`);
		mockGetRcloneConfigPath.mockReturnValue('/mock/rclone.conf');
		mockAppPaths.getTempDir = jest.fn(() => '/mock/temp');

		// Create a mock process with EventEmitter
		mockProcess = new EventEmitter();
		mockProcess.stdout = new EventEmitter();
		mockProcess.stderr = new EventEmitter();
		mockProcess.kill = jest.fn();
		mockProcess.pid = 12345;

		mockSpawn.mockReturnValue(mockProcess as any);

		process.env.ENCRYPTION_KEY = 'test-encryption-key';
		process.env.LOCALAPPDATA = '/mock/localappdata';
	});

	afterEach(() => {
		delete process.env.ENCRYPTION_KEY;
		delete process.env.LOCALAPPDATA;
	});

	it('should resolve with output on successful execution', async () => {
		const expectedOutput = 'backup completed successfully';

		const promise = runResticCommand(['backup', '/test/path']);

		// Simulate process execution
		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from(expectedOutput));
			mockProcess.emit('close', 0);
		});

		const result = await promise;
		expect(result).toBe(expectedOutput);
	});

	it('should reject with error when restic command fails', async () => {
		const errorMessage = 'repository not found';

		const promise = runResticCommand(['backup', '/invalid/path']);

		setImmediate(() => {
			mockProcess.stderr.emit('data', Buffer.from(errorMessage));
			mockProcess.emit('close', 1);
		});

		await expect(promise).rejects.toThrow(errorMessage);
	});

	it('should call onProgress callback with throttled progress updates', async () => {
		const onProgress = jest.fn();
		const progressData = JSON.stringify({
			message_type: 'status',
			percent_done: 0.5,
			bytes_done: 1000,
		});

		const promise = runResticCommand(['backup', '/test'], {}, onProgress);

		setImmediate(() => {
			// Simulate multiple rapid progress updates
			mockProcess.stdout.emit('data', Buffer.from(progressData));
			mockProcess.stdout.emit('data', Buffer.from(progressData));
			mockProcess.stdout.emit('data', Buffer.from(progressData));

			setTimeout(() => {
				mockProcess.emit('close', 0);
			}, 10);
		});

		await promise;

		// Should be called but throttled (not 3 times due to THROTTLE_INTERVAL)
		expect(onProgress).toHaveBeenCalled();
		expect(onProgress.mock.calls.length).toBeLessThan(3);
	});

	it('should call onError callback when error occurs', async () => {
		const onError = jest.fn();
		const errorMessage = 'connection timeout';

		const promise = runResticCommand(['backup', '/test'], {}, undefined, onError);

		setImmediate(() => {
			mockProcess.stderr.emit('data', Buffer.from(errorMessage));
			mockProcess.emit('close', 1);
		});

		try {
			await promise;
		} catch (error) {
			// Expected to throw
		}

		expect(onError).toHaveBeenCalledWith(expect.any(Buffer));
	});

	it('should resolve (not reject) when a backup exits with code 3 (partial read)', async () => {
		const onComplete = jest.fn();
		const summary = JSON.stringify({ message_type: 'summary', total_files_processed: 5 });

		const promise = runResticCommand(['backup', '/test'], {}, undefined, undefined, onComplete);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from(summary));
			mockProcess.stderr.emit('data', Buffer.from('error: could not read /test/locked.db'));
			mockProcess.emit('close', 3);
		});

		await expect(promise).resolves.toBe(summary);
		// onComplete still receives the real exit code so callers can log the warning.
		expect(onComplete).toHaveBeenCalledWith(3);
	});

	it('should still reject with code 3 for a non-backup command', async () => {
		const promise = runResticCommand(['check', '/test']);

		setImmediate(() => {
			mockProcess.stderr.emit('data', Buffer.from('some check error'));
			mockProcess.emit('close', 3);
		});

		await expect(promise).rejects.toMatchObject({ code: 3 });
	});

	it('should attach the exit code to the rejected error', async () => {
		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.stderr.emit('data', Buffer.from('wrong password'));
			mockProcess.emit('close', 12);
		});

		await expect(promise).rejects.toMatchObject({ code: 12 });
	});

	it('should call onComplete callback with exit code', async () => {
		const onComplete = jest.fn();

		const promise = runResticCommand(['backup', '/test'], {}, undefined, undefined, onComplete);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from('done'));
			mockProcess.emit('close', 0);
		});

		await promise;

		expect(onComplete).toHaveBeenCalledWith(0);
	});

	it('should call onProcess callback with spawned process', async () => {
		const onProcess = jest.fn();

		const promise = runResticCommand(
			['backup', '/test'],
			{},
			undefined,
			undefined,
			undefined,
			onProcess
		);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from('done'));
			mockProcess.emit('close', 0);
		});

		await promise;

		expect(onProcess).toHaveBeenCalledWith(mockProcess);
	});

	it('should reject with termination message when process receives SIGTERM', async () => {
		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.emit('exit', null, 'SIGTERM');
		});

		await expect(promise).rejects.toThrow('Process terminated by user');
	});

	it('should reject when spawn fails', async () => {
		const spawnError = new Error('spawn ENOENT');

		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.emit('error', spawnError);
		});

		await expect(promise).rejects.toThrow('Failed to run restic : spawn ENOENT');
	});

	it('should merge custom environment variables', async () => {
		const customEnv = {
			CUSTOM_VAR: 'custom-value',
			RESTIC_PASSWORD: 'test-password',
		};

		const promise = runResticCommand(['backup', '/test'], customEnv);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from('done'));
			mockProcess.emit('close', 0);
		});

		await promise;

		// Verify spawn was called with merged env vars
		expect(mockSpawn).toHaveBeenCalled();
		const spawnOptions = mockSpawn.mock.calls[0][2];
		expect(spawnOptions?.env).toMatchObject(customEnv);
		expect(spawnOptions?.env?.RCLONE_CONFIG_PASS).toBe('test-encryption-key');
	});

	it('should handle non-JSON progress data', async () => {
		const onProgress = jest.fn();
		const plainTextData = 'plain text progress message';

		const promise = runResticCommand(['backup', '/test'], {}, onProgress);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from(plainTextData));
			mockProcess.emit('close', 0);
		});

		await promise;

		expect(onProgress).toHaveBeenCalledWith(Buffer.from(plainTextData));
	});

	// This test requires Windows path semantics (path.basename with backslashes)
	const windowsIt = process.platform === 'win32' ? it : it.skip;
	windowsIt('should replace backslashes in rclone binary path on Windows', async () => {
		const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
		Object.defineProperty(process, 'platform', {
			value: 'win32',
			configurable: true,
		});

		mockGetBinaryPath.mockImplementation((binary: string) =>
			binary === 'rclone' ? 'C:\\mock\\path\\rclone.exe' : `/mock/path/${binary}`
		);

		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from('done'));
			mockProcess.emit('close', 0);
		});

		await promise;

		// Verify the final args use only the basename (no backslashes)
		const spawnArgs = mockSpawn.mock.calls[0][1];
		const rcloneProgramArg = spawnArgs.find((arg: string) => arg.startsWith('rclone.program='));
		expect(rcloneProgramArg).toBeDefined();
		expect(rcloneProgramArg).not.toContain('\\');
		expect(rcloneProgramArg).toBe('rclone.program=rclone.exe');

		// Restore original platform
		if (originalPlatform) {
			Object.defineProperty(process, 'platform', originalPlatform);
		} else {
			delete (process as any).platform;
		}
	});

	it('should not call onError when process is cancelled', async () => {
		const onError = jest.fn();

		const promise = runResticCommand(['backup', '/test'], {}, undefined, onError);

		setImmediate(() => {
			mockProcess.emit('exit', null, 'SIGTERM');
			mockProcess.stderr.emit('data', Buffer.from('some error after cancellation'));
		});

		await expect(promise).rejects.toThrow('Process terminated by user');

		expect(onError).not.toHaveBeenCalled();
	});

	it('should include cache-dir in spawn arguments', async () => {
		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from('done'));
			mockProcess.emit('close', 0);
		});

		await promise;

		const spawnArgs = mockSpawn.mock.calls[0][1];
		expect(spawnArgs).toContain('--cache-dir');
		const cacheDirIndex = spawnArgs.indexOf('--cache-dir');
		expect(spawnArgs[cacheDirIndex + 1]).toContain('restic-cache');
	});

	it('should accumulate multiple stdout data chunks', async () => {
		const chunks = ['chunk1', 'chunk2', 'chunk3'];
		const expectedOutput = chunks.join('');

		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			chunks.forEach(chunk => {
				mockProcess.stdout.emit('data', Buffer.from(chunk));
			});
			mockProcess.emit('close', 0);
		});

		const result = await promise;
		expect(result).toBe(expectedOutput);
	});

	it('should not accumulate streaming backup stdout when progress callback is provided', async () => {
		const onProgress = jest.fn();
		const progressData = JSON.stringify({
			message_type: 'status',
			percent_done: 0.5,
		});

		const promise = runResticCommand(['backup', '/test'], {}, onProgress);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from(progressData));
			mockProcess.stdout.emit('data', Buffer.from(progressData));
			mockProcess.emit('close', 0);
		});

		const result = await promise;
		expect(result).toBe('');
		expect(onProgress).toHaveBeenCalled();
	});

	it('should pipe raw stdout to options.stdout without buffering or parsing', async () => {
		mockProcess.stdout = new PassThrough();
		const received: Buffer[] = [];
		const sink = new Writable({
			write(chunk, _enc, cb) {
				received.push(chunk);
				cb();
			},
		});
		const onProgress = jest.fn();

		const promise = runResticCommand(
			['dump', 'abc123', '/vzdump-qemu-100.vma'],
			{},
			onProgress,
			undefined,
			undefined,
			undefined,
			{ stdout: sink }
		);

		const raw = Buffer.from([0x00, 0xff, 0x7b, 0x7d]);
		mockProcess.stdout.write(raw);
		mockProcess.stdout.end();
		await new Promise(resolve => sink.on('finish', resolve));
		mockProcess.emit('close', 0);

		const result = await promise;
		expect(result).toBe('');
		expect(Buffer.concat(received)).toEqual(raw);
		expect(onProgress).not.toHaveBeenCalled();
	});

	it('should keep only the summary line for streaming backup dry runs', async () => {
		const onProgress = jest.fn();
		const statusData = JSON.stringify({
			message_type: 'status',
			percent_done: 0.5,
		});
		const summaryData = JSON.stringify({
			message_type: 'summary',
			total_files_processed: 10,
		});

		const promise = runResticCommand(['backup', '/test', '--dry-run'], {}, onProgress);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from(`${statusData}\n`));
			mockProcess.stdout.emit('data', Buffer.from(`${summaryData}\n`));
			mockProcess.emit('close', 0);
		});

		const result = await promise;
		expect(result).toBe(summaryData);
	});

	it('should handle verbose_status message type', async () => {
		const onProgress = jest.fn();
		const verboseStatusData = JSON.stringify({
			message_type: 'verbose_status',
			action: 'scan',
			item: '/test/file.txt',
		});

		const promise = runResticCommand(['backup', '/test'], {}, onProgress);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from(verboseStatusData));
			mockProcess.emit('close', 0);
		});

		await promise;

		expect(onProgress).toHaveBeenCalled();
	});

	it('should handle process exit before close', async () => {
		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.emit('exit', 0, null);
			mockProcess.stdout.emit('data', Buffer.from('output'));
			mockProcess.emit('close', 0);
		});

		await expect(promise).resolves.toBe('output');
	});

	it('should handle empty stdout output', async () => {
		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.emit('close', 0);
		});

		const result = await promise;
		expect(result).toBe('');
	});

	it('should pass correct restic binary path to spawn', async () => {
		mockGetBinaryPath.mockImplementation((binary: string) =>
			binary === 'restic' ? '/custom/restic/path' : `/mock/path/${binary}`
		);

		const promise = runResticCommand(['backup', '/test']);

		setImmediate(() => {
			mockProcess.stdout.emit('data', Buffer.from('done'));
			mockProcess.emit('close', 0);
		});

		await promise;

		expect(mockSpawn).toHaveBeenCalledWith(
			'/custom/restic/path',
			expect.any(Array),
			expect.any(Object)
		);
	});

	describe('stall watchdog', () => {
		beforeEach(() => jest.useFakeTimers());
		afterEach(() => jest.useRealTimers());

		it('trips after the full inactivity period and kills the process tree', async () => {
			const promise = runResticCommand(
				['backup', '/test'],
				undefined,
				jest.fn(),
				undefined,
				undefined,
				undefined,
				{ stallTimeout: 60_000 }
			);
			// Attach a catch synchronously so the rejection is never unhandled.
			const settled = expect(promise).rejects.toMatchObject({ stalled: true });

			// One poll (60 s) with no stdout/stderr activity trips the watchdog.
			await jest.advanceTimersByTimeAsync(60_000);

			await settled;
			expect(mockKillProcessTree).toHaveBeenCalledTimes(1);
		});

		it('does not trip while stderr keeps emitting activity', async () => {
			const promise = runResticCommand(
				['backup', '/test'],
				undefined,
				jest.fn(),
				undefined,
				undefined,
				undefined,
				{ stallTimeout: 120_000 }
			);

			// Emit activity before each 60 s poll, so inactivity never reaches 120 s.
			await jest.advanceTimersByTimeAsync(59_000);
			mockProcess.stderr.emit('data', Buffer.from('transferring'));
			await jest.advanceTimersByTimeAsync(59_000);
			mockProcess.stderr.emit('data', Buffer.from('transferring'));
			await jest.advanceTimersByTimeAsync(59_000);

			mockProcess.emit('close', 0);
			await expect(promise).resolves.toBeDefined();
			expect(mockKillProcessTree).not.toHaveBeenCalled();
		});
	});

	describe('timeout', () => {
		beforeEach(() => jest.useFakeTimers());
		afterEach(() => jest.useRealTimers());

		it('kills the process tree with SIGKILL and rejects with timedOut', async () => {
			const promise = runResticCommand(
				['backup', '/test'],
				undefined,
				jest.fn(),
				undefined,
				undefined,
				undefined,
				{ timeout: 5_000 }
			);
			const settled = expect(promise).rejects.toMatchObject({ timedOut: true });

			await jest.advanceTimersByTimeAsync(5_000);

			await settled;
			expect(mockKillProcessTree).toHaveBeenCalledWith(mockProcess, 'SIGKILL');
		});
	});
});

describe('getBackupPlanStats', () => {
	let mockProcess: any;

	beforeEach(() => {
		jest.clearAllMocks();

		mockGetBinaryPath.mockImplementation((binary: string) => `/mock/path/${binary}`);
		mockGetRcloneConfigPath.mockReturnValue('/mock/rclone.conf');
		mockAppPaths.getTempDir = jest.fn(() => '/mock/temp');
		mockGenerateResticRepoPath.mockReturnValue('rclone:storage-name:storage-path');

		mockProcess = new EventEmitter();
		mockProcess.stdout = new EventEmitter();
		mockProcess.stderr = new EventEmitter();
		mockProcess.kill = jest.fn();
		mockProcess.pid = 12345;

		mockSpawn.mockReturnValue(mockProcess as any);

		process.env.ENCRYPTION_KEY = 'test-encryption-key';
	});

	afterEach(() => {
		delete process.env.ENCRYPTION_KEY;
	});

	it('should return stats and snapshot IDs for valid plan', async () => {
		const planId = 'test-plan-123';
		const statsOutput = JSON.stringify({
			total_size: 1024000,
			total_file_count: 100,
		});
		const snapshotsOutput = JSON.stringify([
			{
				id: 'snap1',
				tags: ['plan-test-plan-123', 'backup-backup1'],
			},
			{
				id: 'snap2',
				tags: ['plan-test-plan-123', 'backup-backup2'],
			},
		]);

		let callCount = 0;
		mockSpawn.mockImplementation(() => {
			callCount++;
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				if (callCount === 1) {
					// First call: stats
					process.stdout.emit('data', Buffer.from(statsOutput));
				} else {
					// Second call: snapshots
					process.stdout.emit('data', Buffer.from(snapshotsOutput));
				}
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getBackupPlanStats(planId, 'storage-name', 'storage-path', true);

		expect(result).toEqual({
			total_size: 1024000,
			snapshots: ['backup1', 'backup2'],
		});
		expect(mockGenerateResticRepoPath).toHaveBeenCalledWith('storage-name', 'storage-path');
	});

	it('should return false when planId is missing', async () => {
		const result = await getBackupPlanStats('', 'storage-name', 'storage-path', true);
		expect(result).toBe(false);
	});

	it('should return false when storageName is missing', async () => {
		const result = await getBackupPlanStats('plan-id', '', 'storage-path', true);
		expect(result).toBe(false);
	});

	it('should return false when storagePath is missing', async () => {
		const result = await getBackupPlanStats('plan-id', 'storage-name', '', true);
		expect(result).toBe(false);
	});

	it('should return false when restic command fails', async () => {
		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stderr.emit('data', Buffer.from('repository not found'));
				process.emit('close', 1);
			});

			return process;
		});

		const result = await getBackupPlanStats('plan-id', 'storage-name', 'storage-path', true);
		expect(result).toBe(false);
	});

	it('should handle snapshots without backup tags', async () => {
		const statsOutput = JSON.stringify({ total_size: 5000 });
		const snapshotsOutput = JSON.stringify([
			{
				id: 'snap1',
				tags: ['plan-test-plan', 'other-tag'],
			},
			{
				id: 'snap2',
				tags: ['plan-test-plan'],
			},
		]);

		let callCount = 0;
		mockSpawn.mockImplementation(() => {
			callCount++;
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				if (callCount === 1) {
					process.stdout.emit('data', Buffer.from(statsOutput));
				} else {
					process.stdout.emit('data', Buffer.from(snapshotsOutput));
				}
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getBackupPlanStats('test-plan', 'storage', 'path', false);

		expect(result).toEqual({
			total_size: 5000,
			snapshots: [],
		});
	});

	it('should use empty password when encryption is false', async () => {
		const statsOutput = JSON.stringify({ total_size: 1000 });
		const snapshotsOutput = JSON.stringify([]);

		let callCount = 0;
		let capturedEnv: any;

		mockSpawn.mockImplementation((binary, args, options) => {
			callCount++;
			capturedEnv = options?.env;
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(callCount === 1 ? statsOutput : snapshotsOutput));
				process.emit('close', 0);
			});

			return process;
		});

		await getBackupPlanStats('plan-id', 'storage', 'path', false);

		expect(capturedEnv?.RESTIC_PASSWORD).toBe('');
	});

	it('should handle invalid JSON in stats output', async () => {
		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from('invalid json'));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getBackupPlanStats('plan-id', 'storage', 'path', true);
		expect(result).toBe(false);
	});

	it('should extract multiple backup IDs from snapshots', async () => {
		const statsOutput = JSON.stringify({ total_size: 10000 });
		const snapshotsOutput = JSON.stringify([
			{
				id: 'snap1',
				tags: ['plan-myplan', 'backup-id1', 'device-abc'],
			},
			{
				id: 'snap2',
				tags: ['plan-myplan', 'backup-id2'],
			},
			{
				id: 'snap3',
				tags: ['plan-myplan', 'backup-id3', 'backup-id4'], // Multiple backup tags
			},
		]);

		let callCount = 0;
		mockSpawn.mockImplementation(() => {
			callCount++;
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(callCount === 1 ? statsOutput : snapshotsOutput));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getBackupPlanStats('myplan', 'storage', 'path', true);

		expect(result).toEqual({
			total_size: 10000,
			snapshots: ['id1', 'id2', 'id3'], // First backup- tag from each snapshot
		});
	});
});

describe('getSnapshotByTag', () => {
	let mockProcess: any;

	beforeEach(() => {
		jest.clearAllMocks();

		mockGetBinaryPath.mockImplementation((binary: string) => `/mock/path/${binary}`);
		mockGetRcloneConfigPath.mockReturnValue('/mock/rclone.conf');
		mockAppPaths.getTempDir = jest.fn(() => '/mock/temp');
		mockGenerateResticRepoPath.mockReturnValue('rclone:storage:path');

		mockProcess = new EventEmitter();
		mockProcess.stdout = new EventEmitter();
		mockProcess.stderr = new EventEmitter();
		mockProcess.kill = jest.fn();

		mockSpawn.mockReturnValue(mockProcess as any);

		process.env.ENCRYPTION_KEY = 'test-key';
	});

	afterEach(() => {
		delete process.env.ENCRYPTION_KEY;
	});

	it('should return snapshot when found', async () => {
		const snapshotData = {
			id: 'abc123',
			time: '2025-10-21T10:00:00Z',
			tags: ['backup-test'],
			paths: ['/test/path'],
		};
		const output = JSON.stringify([snapshotData]);

		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getSnapshotByTag('backup-test', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: true,
		});

		expect(result).toEqual({
			success: true,
			result: snapshotData,
		});
	});

	it('should return failure when snapshot not found', async () => {
		const output = JSON.stringify([]);

		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getSnapshotByTag('nonexistent-tag', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: false,
		});

		expect(result).toEqual({
			success: false,
			result: 'Snapshot Not Found',
		});
	});

	it('should return failure when restic command fails', async () => {
		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stderr.emit('data', Buffer.from('authentication failed'));
				process.emit('close', 1);
			});

			return process;
		});

		const result = await getSnapshotByTag('tag', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: true,
		});

		expect(result.success).toBe(false);
		expect(result.result).toContain('Snapshot Not Found');
	});

	it('should handle invalid JSON response', async () => {
		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from('invalid json'));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getSnapshotByTag('tag', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: false,
		});

		expect(result.success).toBe(false);
		expect(result.result).toContain('Snapshot Not Found');
	});

	it('should use encryption key when encryption is true', async () => {
		const output = JSON.stringify([{ id: 'snap1', tags: ['test'] }]);
		let capturedEnv: any;

		mockSpawn.mockImplementation((binary, args, options) => {
			capturedEnv = options?.env;
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		await getSnapshotByTag('test', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: true,
		});

		expect(capturedEnv?.RESTIC_PASSWORD).toBe('test-encryption-key');
	});

	it('should use empty password when encryption is false', async () => {
		const output = JSON.stringify([{ id: 'snap1', tags: ['test'] }]);
		let capturedEnv: any;

		mockSpawn.mockImplementation((binary, args, options) => {
			capturedEnv = options?.env;
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		await getSnapshotByTag('test', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: false,
		});

		expect(capturedEnv?.RESTIC_PASSWORD).toBe('');
	});

	it('should handle snapshot array with no id field', async () => {
		const output = JSON.stringify([{ tags: ['test'], time: '2025-10-21' }]);

		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getSnapshotByTag('test', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: false,
		});

		expect(result).toEqual({
			success: false,
			result: 'Snapshot Not Found',
		});
	});

	it('should return first snapshot when multiple found', async () => {
		const snapshot1 = { id: 'first', tags: ['tag1'] };
		const snapshot2 = { id: 'second', tags: ['tag1'] };
		const output = JSON.stringify([snapshot1, snapshot2]);

		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		const result = await getSnapshotByTag('tag1', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: true,
		});

		expect(result).toEqual({
			success: true,
			result: snapshot1,
		});
	});

	it('should include error message in result on exception', async () => {
		const errorMessage = 'Network connection lost';
		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stderr.emit('data', Buffer.from(errorMessage));
				process.emit('close', 1);
			});

			return process;
		});

		const result = await getSnapshotByTag('tag', {
			storagePath: 'path',
			storageName: 'storage',
			encryption: true,
		});

		expect(result.success).toBe(false);
		expect(result.result).toContain('Snapshot Not Found');
		expect(result.result).toContain(errorMessage);
	});

	it('should call generateResticRepoPath with correct parameters', async () => {
		const output = JSON.stringify([{ id: 'snap1', tags: ['test'] }]);

		mockSpawn.mockImplementation(() => {
			const process = new EventEmitter() as any;
			process.stdout = new EventEmitter();
			process.stderr = new EventEmitter();
			process.kill = jest.fn();

			setImmediate(() => {
				process.stdout.emit('data', Buffer.from(output));
				process.emit('close', 0);
			});

			return process;
		});

		await getSnapshotByTag('my-tag', {
			storagePath: 'custom-path',
			storageName: 'custom-storage',
			encryption: true,
		});

		expect(mockGenerateResticRepoPath).toHaveBeenCalledWith('custom-storage', 'custom-path');
	});

	describe('getSnapshotsByTag', () => {
		const mockOutput = (output: string, code = 0) => {
			const captured: { args?: string[] } = {};
			mockSpawn.mockImplementation((binary, args) => {
				captured.args = args as string[];
				const process = new EventEmitter() as any;
				process.stdout = new EventEmitter();
				process.stderr = new EventEmitter();
				process.kill = jest.fn();
				setImmediate(() => {
					if (code === 0) process.stdout.emit('data', Buffer.from(output));
					else process.stderr.emit('data', Buffer.from(output));
					process.emit('close', code);
				});
				return process;
			});
			return captured;
		};
		const opts = { storagePath: 'path', storageName: 'storage', encryption: false };

		it('returns all snapshots with an id and passes the tag list as is', async () => {
			const captured = mockOutput(JSON.stringify([{ id: 'a' }, { tags: ['x'] }, { id: 'b' }]));

			const result = await getSnapshotsByTag('backup-1,db-main', opts);

			expect(result.map(s => s.id)).toEqual(['a', 'b']);
			const tagIdx = captured.args!.indexOf('--tag');
			expect(captured.args![tagIdx + 1]).toBe('backup-1,db-main');
		});

		it('returns an empty array when no snapshot matches', async () => {
			mockOutput('[]');
			await expect(getSnapshotsByTag('tag', opts)).resolves.toEqual([]);
		});

		it('rejects when restic fails', async () => {
			mockOutput('repository not found', 1);
			await expect(getSnapshotsByTag('tag', opts)).rejects.toThrow();
		});
	});
});

describe('handleResticCheckResult', () => {
	const testContext = {
		repo: '/path/to/repo',
		device: 'test-device-001',
	};

	describe('successful checks', () => {
		it('should handle check with no errors', () => {
			const output = `{
    "message_type": "summary",
    "num_errors": 0,
    "broken_packs": null,
    "suggest_repair_index": false,
    "suggest_prune": false
}
no errors were found`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('No Issue Detected.');
			expect(result.hasError).toBe(false);
			expect(result.fix).toBe('');
			expect(result.logs).toBeInstanceOf(Array);
			expect(result.logs.length).toBeGreaterThan(0);
		});

		it('should handle check with verbose success output', () => {
			const output = `Loading index
Checking packs
Checking snapshots
Checking data blobs
no errors were found`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('No Issue Detected.');
			expect(result.hasError).toBe(false);
			expect(result.fix).toBe('');
		});
	});

	describe('damaged repository index', () => {
		it('should detect damaged index and provide fix', () => {
			const output = `Loading index
The repository index is damaged
error: index file corrupted`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('The repository index is damaged.');
			expect(result.hasError).toBe(true);
			expect(result.fix).toContain('restic repair index');
			expect(result.fix).toContain(testContext.repo);
			expect(result.fix).toContain(testContext.device);
			expect(result.fix).toContain('Pluton Encryption key');
		});

		it('should provide proper repair command for damaged index', () => {
			const output = `The repository index is damaged
Cannot read index file
error: check failed`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('The repository index is damaged.');
			expect(result.fix).toContain(`restic repair index -r ${testContext.repo}`);
		});
	});

	describe('ciphertext verification failures', () => {
		it('should detect ciphertext verification failure', () => {
			const output = `Loading pack 1234567890abcdef
ciphertext verification failed
error: decryption error`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('Ciphertext verification failed.');
			expect(result.hasError).toBe(true);
			expect(result.fix).toContain('hard to fix');
			expect(result.fix).toContain('hardware problems');
			expect(result.fix).toContain('Restic forum');
		});

		it('should provide appropriate guidance for ciphertext issues', () => {
			const output = `ciphertext verification failed for blob
error: authentication failed`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('Ciphertext verification failed.');
			expect(result.fix).toContain('IRC channel');
			expect(result.fix).not.toContain('restic repair');
		});
	});

	describe('authorization failures', () => {
		it('should detect failed authorization', () => {
			const output = `Connecting to repository
failed to authorize account
error: access denied`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('Storage Authorization failed.');
			expect(result.hasError).toBe(false);
			expect(result.fix).toBe('');
		});

		it('should handle authorization failure without treating as error', () => {
			const output = `failed to authorize account: invalid credentials
Cannot access repository`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('Storage Authorization failed.');
			expect(result.hasError).toBe(false);
		});
	});

	describe('logs processing', () => {
		it('should filter out empty lines from logs', () => {
			const output = `Line 1

Line 2

Line 3`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.logs).toEqual(['Line 1', 'Line 2', 'Line 3']);
			expect(result.logs.length).toBe(3);
		});

		it('should trim whitespace and filter empty lines', () => {
			const output = `  Line 1  
   
Line 2
   
  Line 3  `;

			const result = handleResticCheckResult(output, testContext);

			expect(result.logs.length).toBe(3);
			expect(result.logs).not.toContain('');
		});

		it('should include all non-empty lines in logs', () => {
			const output = `Loading index
Checking packs
Checking snapshots
no errors were found`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.logs).toContain('Loading index');
			expect(result.logs).toContain('Checking packs');
			expect(result.logs).toContain('Checking snapshots');
			expect(result.logs).toContain('no errors were found');
		});
	});

	describe('multiple issues', () => {
		it('should handle multiple error conditions where last one sets the message', () => {
			const output = `The repository contains damaged pack files
pack 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef: error
The repository index is damaged
no errors were found`;

			const result = handleResticCheckResult(output, testContext);

			// All conditions are checked and message gets set multiple times
			// Last condition "no errors were found" sets message and hasError
			expect(result.message).toBe('No Issue Detected.');
			expect(result.hasError).toBe(false);
		});

		it('should handle damaged pack file without success message', () => {
			const output = `The repository contains damaged pack files
pack 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef: error
The repository index is damaged`;

			const result = handleResticCheckResult(output, testContext);

			// Both conditions are true, but index message comes last
			expect(result.message).toBe('The repository index is damaged.');
			expect(result.hasError).toBe(true);
		});

		it('should handle multiple error conditions and last success message', () => {
			const output = `ciphertext verification failed
failed to authorize account
no errors were found`;

			const result = handleResticCheckResult(output, testContext);

			// All three conditions are true, last one wins for message
			expect(result.message).toBe('No Issue Detected.');
			// But authorization failure sets hasError to false
			expect(result.hasError).toBe(false);
		});
	});

	describe('edge cases', () => {
		it('should handle empty output', () => {
			const output = '';

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('');
			expect(result.hasError).toBe(true);
			expect(result.fix).toBe('');
			expect(result.logs).toEqual([]);
		});

		it('should handle output with only whitespace', () => {
			const output = '   \n\n   \n   ';

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('');
			expect(result.logs).toEqual([]);
		});

		it('should handle unknown error format', () => {
			const output = `Some unknown error occurred
Check failed for unknown reason`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('');
			expect(result.hasError).toBe(true);
			expect(result.logs.length).toBe(2);
		});
	});

	describe('repository context', () => {
		it('should use provided repository path in fix commands', () => {
			const customContext = {
				repo: '/custom/repo/path',
				device: 'my-device',
			};
			const output = `The repository index is damaged`;

			const result = handleResticCheckResult(output, customContext);

			expect(result.fix).toContain('/custom/repo/path');
			expect(result.fix).toContain('my-device');
		});
	});

	describe('real-world scenarios', () => {
		it('should handle typical successful check output', () => {
			const output = `using temporary cache in /tmp/restic-check-cache-123456
repository 1a2b3c4d opened (version 2, compression level auto)
created new cache in /tmp/restic-check-cache-123456
create exclusive lock for repository
load indexes
check all packs
check snapshots, trees and blobs
[0:00] 100.00%  3 / 3 snapshots
no errors were found`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('No Issue Detected.');
			expect(result.hasError).toBe(false);
			expect(result.fix).toBe('');
			expect(result.logs.length).toBeGreaterThan(5);
		});

		it('should handle corrupted repository scenario', () => {
			const output = `using temporary cache in /tmp/restic-check-cache-123456
repository 1a2b3c4d opened (version 2, compression level auto)
Load(<data/1234567890abcd>, 0, 0) returned error, retrying after 552.330144ms: ciphertext verification failed
Load(<data/1234567890abcd>, 0, 0) returned error, retrying after 552.330144ms: ciphertext verification failed
ciphertext verification failed
Fatal: repository contains errors`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('Ciphertext verification failed.');
			expect(result.hasError).toBe(true);
			expect(result.fix).toContain('hardware problems');
		});

		it('should handle authentication error scenario', () => {
			const output = `Fatal: create repository at s3:s3.amazonaws.com/backup failed: failed to authorize account: Forbidden`;

			const result = handleResticCheckResult(output, testContext);

			expect(result.message).toBe('Storage Authorization failed.');
			expect(result.hasError).toBe(false);
		});
	});
});