fixing typo and moving grab file into else clause
[migration-tools.git] / mig-bin / mig-iconv
1 #!/usr/bin/perl -w
2 ###############################################################################
3 =pod
4
5 =head1 NAME
6
7 mig-iconv 
8
9 Attempts to invoke B<iconv> on the specified tracked file, placing the
10 output in [file].iconv
11
12 If given no other arguments, the invocation will lool like
13
14 =over 5
15
16 iconv -f ISO-8859-1 -t UTF-8 -o <file>.utf8 <file>
17
18 =back
19
20 otherwise, the arguments will be passed through like so
21
22 =over 5
23
24 iconv [other arguments...] -o <file>.utf8 <file>
25
26 =back
27
28 You'll need to invoke B<mig-add> prior to using commands like B<mig-iconv>
29
30 =head1 SYNOPSIS
31
32 B<mig-iconv> <file> [other arguments...]
33
34 =cut
35
36 ###############################################################################
37
38 use strict;
39 use Switch;
40 use Env qw(
41     HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
42     MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
43 );
44 use Pod::Usage;
45 use DBI;
46 use Cwd 'abs_path';
47 use FindBin;
48 my $mig_bin = "$FindBin::Bin/";
49 use lib "$FindBin::Bin/";
50 use Mig;
51
52 pod2usage(-verbose => 2) if ! $ARGV[0] || $ARGV[0] eq '--help';
53
54 Mig::die_if_no_env_migschema();
55 Mig::die_if_mig_tracking_table_does_not_exist();
56
57 my $file = abs_path($ARGV[0]);
58 if ($file =~ /^$MIGBASEWORKDIR/) {
59     call_iconv(@ARGV);
60 } else {
61     print "File falls outside of MIGWORKDIR ($MIGWORKDIR): $file\n";
62 }
63
64 exit 0;
65
66 ###############################################################################
67
68 sub call_iconv {
69     my $file = abs_path(shift);
70     my @args = @_;
71
72     my $tracked_file_id = Mig::check_for_tracked_file($file);
73     if ($tracked_file_id) {
74         my $data = Mig::status_this_file($file);
75         print "iconv'ing tracked file: $file\n";
76
77         if (scalar(@args) == 0) {
78             @args = (
79                  '-f'
80                 ,'ISO-8859-1'
81                 ,'-t'
82                 ,'UTF-8'
83                 ,'--verbose'
84             );
85         }
86
87         system('iconv', @args, '-o', $file . '.utf8', $file);
88         system('touch', $file . '.utf8'); # handle 0-byte files
89
90         my $dbh = Mig::db_connect();
91         my $utf8_file = $dbh->quote($file . '.utf8');
92         if (! -e $file . '.utf8') {
93             print "utf8 file does not exist: $utf8_file\n";
94             $utf8_file = $dbh->quote('');
95         }
96
97         my $rv = $dbh->do("
98             UPDATE $MIGSCHEMA.tracked_file
99             SET utf8_filename = $utf8_file
100             WHERE base_filename = " . $dbh->quote($file) . "
101             ;
102         ") || die "Error inserting into table $MIGSCHEMA.tracked_file: $!\n";
103         Mig::db_disconnect($dbh);
104     } else {
105         print "File not currently tracked: $file\n";
106     }
107 }