use Modern::Perl;
use File::Slurper qw(read_dir read_text write_text);

sub tag {
  $_ = shift;
  s/ /_/g;
  return "#$_";
}

for my $fn (read_dir('wiki')) {
  next unless $fn =~ /\.md$/;
  $fn = "wiki/$fn";
  my $text = read_text($fn);
  my $changed = $text =~ s/^Tags: //m;
  $changed += $text =~ s/\[\\?#?(.*?)\]\(\/search[^)]*\)/tag($1)/ge;
  next unless $changed;
  my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
      $atime,$mtime,$ctime,$blksize,$blocks)
      = stat($fn);
  rename($fn, $fn . '~');
  write_text($fn, $text);
  utime($atime, $mtime, $fn);
}