Just some misc clean-up to Alan's stuff.
[backups/.git] / main.cpp
1 #include <iostream>
2 #include <fstream>
3 #include <iterator>
4 #include <algorithm>
5 #include <cassert>
6 #include <ctime>
7
8 #include "filedata.hpp"
9
10 using namespace std;
11
12 static unsigned int bytes_in_block;
13 static const char * dbname_in = getenv("backupdbin");
14 static const char * dbname_out = getenv("backupdbout");
15
16 unsigned long long read_time( istream &i ) {
17   string date_string;
18
19   int c;
20   // Todo, don't use char_traits<char> directly here
21   for( c = i.get(); 0 != c && char_traits<char>::eof() != c; c = i.get() ) {
22     date_string.push_back( c );
23   }
24   if( char_traits<char>::eof() == c ) { i.setstate( ios_base::eofbit ); }
25
26   return atoll( date_string.c_str() );
27 }
28
29 template<class I, class O, class INT>
30 bool copy_until_full( I begin, I end, O out, INT &space ) {
31   bool complete = true;
32
33   while( 0 != space && begin != end ) {
34     INT size = (*begin)->getFileSize();
35     INT blocksize = blocks( size ) * bytes_in_block;
36
37     if( blocksize <= space ) {
38       space -= blocksize;
39       *out = *begin;
40       ++out;
41     } else {
42       // We missed a file that should be included so the backup is not complete
43       complete = false;
44     }
45     ++begin;
46   }
47   return complete;
48 }
49
50 template<class SET>
51 void populate_set( istream &in, SET &files ) {
52   do {
53     FileData *data = new FileData();
54     in >> data;
55     if( data->getFileName().size() ) {
56       files.insert( data );
57     } else {
58       delete data;
59     }
60   } while( ! in.eof() );
61 }
62
63 template<class SET>
64 void partition_sets( const SET &current, const SET &old,
65                      SET &added, SET &common, SET &old_common, SET &deleted  ) {
66   set_difference(   current.begin(), current.end(),
67                     old.begin(),     old.end(),
68                     inserter( added, added.begin() ),
69                     FileData::namecmp );
70
71   set_difference(   old.begin(),     old.end(),
72                     current.begin(), current.end(),
73                     inserter( deleted, deleted.begin() ),
74                     FileData::namecmp );
75
76   set_intersection( current.begin(), current.end(),
77                     old.begin(),     old.end(),
78                     inserter( common, common.begin() ),
79                     FileData::namecmp );
80
81   set_intersection( old.begin(),    old.end(),
82                     common.begin(), common.end(),
83                     inserter( old_common, old_common.begin() ),
84                     FileData::namecmp );
85 }
86
87 template<class INT>
88 INT blocks( const INT &bytes ) {
89   INT numblocks = bytes / bytes_in_block;
90   if( 0 != bytes % bytes_in_block ) numblocks++;
91
92   return numblocks;
93 }
94
95 template<class ITER, class INT>
96 void sizes( ITER begin, const ITER &end, INT &numblocks, INT &numbytes ) {
97   numblocks = 0;
98   numbytes  = 0;
99
100   while( begin != end ) {
101     INT filesize = (*begin)->getFileSize();
102
103     numbytes  += filesize;
104     numblocks += blocks( filesize );
105     ++begin;
106   }
107 }
108
109 template<class I, class O>
110 void copy_filenames( I begin, const I &end, O out ) {
111   while( begin != end ) {
112     string output = (*begin)->getFileName();
113     output.push_back( 0 );
114     *out = output;
115     ++out;
116     ++begin;
117   }
118 }
119
120 template<class ITER>
121 void updateLastBackupDate( ITER begin, const ITER &end, unsigned long long date ) {
122   while( begin != end ) {
123     (*begin)->setLastBackupDate( date );
124     ++begin;
125   }
126 }
127
128 template<class ITER>
129 void delete_objects( ITER begin, const ITER &end ) {
130   while( begin != end ) {
131     delete *begin;
132     ++begin;
133   }
134 }
135
136 int main() {
137
138   // Check to make sure required env variables are set
139   if( getenv( "backupdbin"  ) == NULL ||
140       getenv( "backupdbout" ) == NULL ||
141       getenv( "blocksize"   ) == NULL ||
142       getenv( "availsizemb" ) == NULL )
143   {
144      cerr << "Required environment variables are not set. Exiting." << endl;
145      return 1;
146   }
147
148   // Setup our bytes_in_block value
149   bytes_in_block = atoll(getenv("blocksize"));
150
151   // Get the date on stdin
152   unsigned long long now = read_time( cin );
153
154   // Parse the list of current files on stdin
155   file_set current;
156   populate_set( cin, current );
157
158   file_set backed_up;
159   ifstream db( dbname_in );
160   if( db && db.good() ) {
161     populate_set( db, backed_up );
162   }
163
164   // Now divide the two sets into three sets (added, deleted and common )
165   file_set added, deleted, common, old_common;
166   partition_sets( current, backed_up, added, common, old_common, deleted );
167
168   // Now find the list of files to backup.
169   file_set backups;
170
171   // backup all added files
172   copy( added.begin(), added.end(), inserter( backups, backups.begin() ) );
173
174   // Track the total size of added files
175   unsigned long long added_blocks, added_bytes;
176   sizes( added.begin(), added.end(), added_blocks, added_bytes );
177
178   file_vector modified_v;
179   // Backup files that have been modified
180   file_set::iterator i = common.begin(), j = old_common.begin();
181   for( ; i != common.end(); ++i, ++j ) {
182     (*i)->setLastBackupDate( (*j)->getLastBackupDate() );
183
184     if( needs_backup( *j, *i ) ) modified_v.push_back( *i );
185   }
186
187   copy( modified_v.begin(), modified_v.end(), inserter( backups, backups.begin() ) );
188
189   // Track the total size of modified files
190   unsigned long long modified_blocks, modified_bytes;
191   sizes( modified_v.begin(), modified_v.end(), modified_blocks, modified_bytes );
192
193   // Now, sort the backups by filesize (decreasing) and build a list that'll fit
194   // on a DVD
195   file_vector backups_s;
196   copy( backups.begin(), backups.end(), back_inserter( backups_s ) );
197
198   sort( backups_s.rbegin(), backups_s.rend(), FileData::sizecmp );
199
200   file_set final;
201   const unsigned long long availsizemb = atoll( getenv("availsizemb") ) * 0x100000ull;
202   unsigned long long space = availsizemb;
203
204   insert_iterator<file_set> final_i( final, final.begin() );
205
206   // Copy files over until full or out of files
207   bool complete
208     = copy_until_full( backups_s.begin(), backups_s.end(), final_i, space );
209
210   // Track the size filled up by essential backups
211   unsigned long long essential_blocks, essential_bytes;
212   sizes( final.begin(), final.end(), essential_blocks, essential_bytes );
213
214   // Now, sort the non-backed-up list by last_backup_date, then by filesize
215   // (decreasing) and back-fill.  This should minimize the number of DVDs in the
216   // collection left with actual content.
217   if( 0 != space ) {
218     file_vector leftovers;
219     set_difference( current.begin(), current.end(),
220                     final.begin(),   final.end(),
221                     back_inserter( leftovers ),
222                     FileData::namecmp );
223
224     // Achieve 'last backup date then by filesize' by first sorting by filesize
225     // and then running stable sort by last backup date.
226     sort(        leftovers.rbegin(), leftovers.rend(), FileData::sizecmp );
227     stable_sort( leftovers.begin(),  leftovers.end(),  FileData::lastbackupcmp );
228
229     copy_until_full( leftovers.begin(), leftovers.end(), final_i, space );
230   }
231
232   // Track the total size to be copied to the dvd
233   unsigned long long total_blocks, total_bytes;
234   sizes( final.begin(), final.end(), total_blocks, total_bytes );
235
236   // Track how many disks there are remaining to be burned
237   unsigned long long disks_remaining = 0;
238   if(modified_bytes || added_bytes)
239     disks_remaining = static_cast<unsigned long long>(
240         ceil( static_cast<double>( modified_bytes + added_bytes ) / availsizemb ) - 1
241         );
242
243   updateLastBackupDate( final.begin(), final.end(), now );
244
245   // Write the 'current' list to the dbfile
246   ofstream dbout( dbname_out );
247   copy( current.begin(), current.end(), ostream_iterator<FileData*>( dbout ) );
248
249   // Write the 'final' list to stdout
250   copy_filenames( final.begin(), final.end(), ostream_iterator<string>( cout ) );
251
252   cerr << now << endl << endl;
253
254   cerr << "Need backing up..." << endl;
255   cerr << "     Added Bytes:            " << added_bytes << endl;
256   cerr << "     Added Blocks:           " << added_blocks << endl;
257   cerr << "     Modified Bytes:         " << modified_bytes << endl;
258   cerr << "     Modified Blocks:        " << modified_blocks << endl;
259   cerr << "       Disks Remaining:      " << disks_remaining << endl << endl;
260
261   cerr << "Will be backed up..." << endl;
262   cerr << "     Essential Bytes:        " << essential_bytes << endl;
263   cerr << "     Essential Blocks:       " << essential_blocks << endl;
264   cerr << "     Total Bytes:            " << total_bytes << endl;
265   cerr << "     Total Blocks:           " << total_blocks << endl << endl;
266
267   if( ! complete ) { cerr << "Backup is incomplete!" << endl; }
268
269   // Clean-up
270   delete_objects( backed_up.begin(), backed_up.end() );
271   delete_objects( current.begin(),   current.end() );
272 }