#!/usr/bin/perl

# BEGIN{
#  $| = 1;
#  print "Content-type: text/plain\n\n";
#  open(STDERR, ">&STDOUT");
# }

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# SmartView Replacer
# (C) 2011 R.S., All Rights Reserved.
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

use strict;
use warnings;

my $Ver = "1.0";

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Settings
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

my $Charset = "utf-8";
my $ViewPort = '<meta name="viewport" content="width=device-width, initial-scale=$InitialScale, user-scalable=$UserScalable, maximum-scale=$MaximumScale">';

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Add viewport
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 my $ReplaceFileName = $ENV{'SCRIPT_NAME'};
 $ReplaceFileName =~ s|.*/([^/]+)\.cgi$|$1\.html|;
 
 my @Contents = ();
 open(IN, $ReplaceFileName) || &Error("File not found.");
 @Contents = <IN>;
 close(IN);
 
 my $UA = $ENV{'HTTP_USER_AGENT'};
 
 print "Content-type: text/html;charset=$Charset\n\n";
 
 my $Line;
 foreach $Line (@Contents) {
  if ($UA =~ /iPhone|iPod|Android|BlackBerry|IEMobile/) {
   $Line =~ s|id=\"([\w-]+)\"|id=\"\1_SP\"|i;
   $Line =~ s|class=\"([\w-]+)\"|class=\"\1_SP\"|i;
   if ($Line =~ /<head>/i) {
    print $Line . "\n  " . $ViewPort;
   } elsif ($Line =~ /<img/) {
    $Line =~ s|src=\"([^/]+)\.([\w]+)\"|src=\"\1\_sp\.\2\"|i;
    print $Line;
   } else {
    print $Line;
   }
  } else {
   print $Line;
  }
 }


# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Error
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

sub Error {
 print "Content-type: text/html;charset=shift_jis\n\n";
 print "<!doctype html><head><title>Error</title>$ViewPort</head><body><section><p>$_[0]</p></section></body></html>";
 exit;
}

exit;
