#!/usr/bin/perl -w

use strict;

my $text;
my $var;

sub Usage() {
  print "Usage:\n  add_text.pl attr=text files...\n";
  exit(1);
}

sub run($) {
  my $file = shift;
  lstat($file);
  return 0 unless -f _;
  return 0 unless open(FH, "$file");
  my @line = <FH>;
  close(FH);
  if (grep(m/$text/, @line )) { # already there
    return 0;
  }

  my @new;
  my $pos = undef;
  my $flag = 1;
  for (@line) {
    if ($flag) {
      if ($pos) {
	if (m/^device=/) { # put new text 200 above the device text
	  $pos =~ m/^T[ \t](\d+)[ \t]+(\d+)(.*)$/;
	  my $y = $2 + 200;
	  push @new, "T $1 $y$3\n";
	  push @new, "$text\n";
	  $flag = 0;
	}
	if (m/^$var=/) {
	  # ignore old value
	} else {
	  push @new, $pos;
	  push @new, $_;
	}
	$pos = undef;
      } else {
	if (m/^T[ \t]+/) {
	  $pos = $_;
	} else {
	  push @new, $_;
	}
      }
    } else {
      push @new, $_;
    }
  }

  if ($flag) {
    # no "device=..", put it anywhere
    push @new, "T 1000 1000 5 10 0 0 0 0 1\n";
    push @new, "$text\n";
  }

  return 0 unless open(FH, ">$file.new");
  print FH @new;
  close(FH);
  `mv $file $file.old`;
  `mv $file.new $file`;
}

if (@ARGV < 1) {
  Usage();
}
$text = shift;
$var = undef;
if ($text =~ m/^(.+)=/) {
  $var = $1;
} else {
  Usage();
}

for (@ARGV) {
  run($_);
}
