#! /usr/bin/env ruby # frozen_string_literal: true # Only use stdlib, no gems BS, no rails BS :) dir_name = ARGV[0] pcap_count = ARGV[1].to_i compressed = ARGV[2].to_i unless File.directory?(File.expand_path(dir_name)) warn "Directory #{dir_name} does not exits. Exiting." exit 1 end Dir.chdir(dir_name) files_h = {} Dir.foreach(dir_name) do |file| next if (file == '.') || (file == '..') # Compressed file modification time will be filename, for example: # capture00_1590423684.pcap.zst if compressed == 1 && file =~ /^capture(\d+)_(\d{10,})\.pcap\.zst$/ timestamp = Regexp.last_match(2).to_i file_number = Regexp.last_match(1) files_h[timestamp] = file_number # Get uncompressed file modification time from file mtime itself elsif file =~ /^capture(\d+)$/ file_number = Regexp.last_match(1) timestamp = File.mtime(file).to_i # p file_number, timestamp files_h[timestamp] = file_number if compressed == 1 old_file = "capture#{file_number}" new_file = "capture#{file_number}_#{timestamp}.pcap.zst" File.delete(new_file) if File.exist?(new_file) system('/usr/bin/zstd', old_file, '-o', new_file, '--rm') end end end exit 0 if files_h.empty? new_number = pcap_count - 1 zero_count = new_number.to_s.length files = files_h.sort_by { |k, _v| -k } files.each do |timestamp, number| old_prefix = "capture#{number}" new_number_string = format "%0#{zero_count}d", new_number new_prefix = "capture#{new_number_string}" if compressed == 1 file_suffix = "_#{timestamp}.pcap.zst" else file_suffix = '' end file_old = old_prefix + file_suffix file_new = new_prefix + file_suffix if File.exist?(file_old) if File.exist?(file_new) File.rename(file_new, 'temp_file') File.rename(file_old, file_new) File.rename('temp_file', file_old) else File.rename(file_old, file_new) end end new_number -= 1 break if new_number < 0 end