#!/usr/bin/perl -w
use strict;
use AutoLoader;
use CGI qw(:standard :upload);
use Cwd;
use Digest::MD5 qw(md5_hex);

# # Module environment init.
# my $moduleshome = $ENV{MODULESHOME}?$ENV{MODULESHOME}:"/pdc/modules/etc";
# require "$moduleshome/init/perl";
# # Add sbc-specific modules.
# module("load sbc");
# # Add sbcweb development env variables, see module display sbcweb for
# # details.
# module("load sbcweb");
# module("load easy");
# module("load heimdal");

# my $SBCWEB_SCRATCH = $ENV{SBCWEB_SCRATCH};
# my $SBCWEB_URL = $ENV{SBCWEB_URL};
# my $SBCWEB_SCRATCH_URL = $ENV{SBCWEB_SCRATCH_URL};
# my $SBCWEB_CLEANUP_INTERVAL = 10;
my $NODES = "1S";
my $MINTIME = 180;
my $CAC = "sbc.sbcweb";
#my $LOGIN_NODE = "scratchy.pdc.kth.se";

#------------------------------------------------------------------------
my $MAINTAINER = 'maccallr@sbc.su.se';
my $DISORDERCGIDIR = 'http://www.sbc.su.se/~maccallr/disorder/cgi-bin';
my $MINLENGTH = 20;
my $MAXLENGTH = 4000;
#------------------------------------------------------------------------

print header;
print disorder_start_html();



my $scratch = "/home/maccallr/public_html/disorder/cgi-bin/cache";
unless (0 && -d $scratch) {
  mkdir $scratch, 0755;
  # let bob read files there == NOT ALLOWED ANYMORE...
  # system "fs sa $scratch maccallr write";
  # keep data there secure - only readable by those
  # who know the md5 keys
  # system "fs sa $scratch system:anyuser none";
}

print disorder_title();


if (param()) {
  my $seq = uc(param('seq'));
  $seq =~ s/^>.+$//mg;
  $seq =~ s/[^A-Z]//g;
  my $length = length($seq);

  if ($length >= $MINLENGTH && $length <= $MAXLENGTH && $seq !~ /[OBJUZ]/) {
    my $md5 = md5_hex($seq);

    # write the fasta file
    my $fastadir = "$scratch/fasta";
    mkdir $fastadir, 0755 unless (-d $fastadir);
    my $fastafile = "$fastadir/$md5.fasta";

    my $caspdir = "$scratch/casp";
    mkdir $caspdir, 0755 unless (-d $caspdir);

    if (! -s $fastafile) {
      if (open(FASTA, ">$fastafile")) {
	print FASTA ">$md5\n$seq\n";
	close(FASTA);
        open(PEND, ">$fastadir/$md5.pending");
        close(PEND);
      } else {
	print mypara(font({-color=>'red'}, "WARNING: "), "there was a problem
            submitting your job to the DRIP-PRED server (could not create
            input file), please contact the server owner: $MAINTAINER
            to have the problem fixed."), end_html;
	exit;
      }

#      my $pwd = cwd;
#      my $JOBCMD = "./runandmail.pl -cachedir $scratch -md5 $md5";

#      my $JOBTIME = $length < $MINTIME ? $MINTIME : $length;

#      my $JID = `cd $pwd ; nohup $JOBCMD 2>&1 &`;
#      my $JID = `cd $pwd ; /pdc/vol/easy/1.6/bin/esubmit -m -v -n $NODES -t $JOBTIME -c $CAC $JOBCMD 2>&1`;
#      my $JID = `rsh -F $LOGIN_NODE 'cd $pwd ; $JOBCMD' 2>&1`;

#      unless ($JID =~ /^\d+$/) {
#	print mypara(font({-color=>'red'}, "WARNING: "), "there was a problem
#            submitting your job to the DRIP-PRED server (could not queue job),
#            please contact the server owner: $MAINTAINER
#            to have the problem fixed."), "info:", pre($JID),
#	      end_html;
#
#	# remove fastafile
#	unlink $fastafile;
#	exit;
#      }
#      chomp($JID);
#      my $jiddir = "$scratch/jid";
#      mkdir $jiddir, 0755 unless (-d $jiddir);
#      if (open(JID, ">$jiddir/$md5")) {
#	print JID "$JID\n";
#	close(JID);
#      }
    }
    print mypara("Thank you. Your sequence was $length residues long.
          It has been given the job identifier <tt>$md5</tt>.
          The prediction requires a PSI-BLAST run so it will be processed by our queueing system and could take up 8 hours depending on available computing resources.  You can monitor the progress of your job and view the results at ", a({-href=>"results.cgi?md5=$md5"}, "this location."));

    my ($email) = param('email') =~ /([\w+.-]+\@([\w-]+\.)+[\w-]+)/;
    if ($email) {
      print mypara("Also, the results will be emailed to you at $email");

      if (open(CASP, "$caspdir/$md5")) {
	# maybe the results are already there, so they
        # need to be sent by email again

	my $tag = param('jobname') || $md5;
	$tag =~ s/\s+/ /g; # remove any newlines, which might be insecure

	if (open(MAIL, "|/usr/sbin/sendmail -t")) {
	  print MAIL "To: $email
From: disorder\@sbc.su.se
Subject: DRIP-PRED results $tag

Your results are ready and may be viewed at:
$DISORDERCGIDIR/results.cgi?md5=$md5

The CASP5 formatted results follow:

";
	  while (<CASP>) {
	    s/$md5/$tag/; # for the TARGET line
	    if ($email =~ /predictioncenter\.org/) {
	      s/AUTHOR (\S+)/AUTHOR 7772-6045-2667/;
	    }

	    print MAIL $_;
	  }
	  close(MAIL);
	}
	close(CASP);
      } else {
	# append address to file
	# (multiple people could send the same sequence)
	# results will be sent to these addresses after calculation
	my $emaildir = "$scratch/email";
	mkdir $emaildir, 0755 unless (-d $emaildir);
	if (open(EMAIL, ">>$emaildir/$md5")) {
	  print EMAIL "$email\n";
	  close(EMAIL);
	}
      }

      # if email was given, they might have also given a jobname
      # so we save the email/jobname pair in a file (see runandmail.pl)
      my ($jobname) = param('jobname') || '';
      if ($jobname) {
	$jobname =~ s/\s+/ /g; # newlines might be a problem
	my $jobnamedir = "$scratch/jobname";
	mkdir $jobnamedir, 0755 unless (-d $jobnamedir);
	if (open(JOBNAME, ">>$jobnamedir/$md5")) {
	  print JOBNAME "$email $jobname\n";
	  close(JOBNAME);
	}
      }

    } else {
      print mypara("You didn't give an email address, so make sure
you bookmark the link above and check back every 20 minutes or so.");
    }
  } else {
    print p("That wasn't a nice sequence, please go back and try again.  Sequence must be between $MINLENGTH and $MAXLENGTH residues long and should not contain non-standard amino-acid codes.");
  }
} else {

print mypara('This is an experimental server for predicting structurally <b>D</b>isordered <b>R</b>egions <b>I</b>n <b>P</b>roteins.  Structural disorder is predicted by looking for sequence patterns that are not typically found in the <a href="http://www.rcsb.org/pdb/">PDB</a>.  The method also incorporates <a href="http://bioinf.cs.ucl.ac.uk/psipred/">PSIPRED</a> predictions.  Full details of the method can be found in this <a href="http://www.forcasp.org/paper2127.html">FORCASP paper</a>.');

#  print disclaimer();

  print start_form({-action=>'submit.cgi'});

  print p(b("For protein-by-protein research use only.  No automated requests please."));
  print "Give your email address if you want to receive the results by email:", br, "\n";
  print textfield(-name=>'email', -size=>40),
    small("(processing can take a few hours)"), br, "\n";

  print "Enter <i>one</i> single-letter protein sequence in the box below (numbers will be stripped):", br;
  print textarea(-name=>'seq',
  	       -default=>'',
  	       -rows=>10,
  	       -columns=>80,
  	      ), br, textfield(-name=>'jobname'),
		small(" <-- give your job a name (optional)"), br;
  print submit, '&nbsp', reset, '&nbsp;',
    small('[ maybe you need to visit ', a({-href=>'http://www.expasy.org/sprot/', -target=>'sp'}, 'Swiss-Prot'), ' to find your sequence? ]'), end_form;

  print p(small("Back to the ", a({-href=>"http://www.sbc.su.se/~maccallr/disorder/"}, "DRIP-PRED homepage...")));

  print authors();
}

print end_html;


sub authors {
  return table({-width=>600, -border=>0, -cellspacing=>0, -cellpadding=>2},
	      Tr(td({-style=>'background: #ddf9f9;'}, small("Author: Bob MacCallum, Stockholm Bioinformatics Center, Stockholm University, Sweden.")),
		 td(a({-href=>"http://www.sbc.su.se"}, img({-src=>'http://www.sbc.su.se/~maccallr/sbclogo150.png', -border=>0, -width=>150, -height=>33, -alt=>'SBC logo'})))
		));
}

sub mypara {
  return table({-width=>600, -border=>0, -cellspacing=>0, -cellpadding=>0}, Tr(td((@_)))).br."\n";
}

sub disclaimer {
  return mypara(i("Please note: this service has not yet been released to
the public.  It may change or move at any time.  Please address all
comments to Bob MacCallum at maccallr\@sbc.su.se - thank you!"));
}

sub placeholder {
  my ($filename, $JID) = @_;
  if (open(PLACE, ">$filename")) {
    print PLACE disorder_start_html(),
      disorder_start_html(), disorder_title(), "\n";
    print PLACE mypara("Job status: ", b("queued"));

    print PLACE mypara("Please wait for your results - they will appear here when they are ready.  If you gave us your email address, you will receive a notification email.  Otherwise, please bookmark this page and check back regularly."), "\n";

#    print PLACE mypara("You may also monitor the progress of your job in our queueing system by following ", a({-href=>"$SBCWEB_URL/cgi-bin/tools/easy_job_status.pl?$JID"}, "this link"), ".");

    print PLACE end_html();
    close(PLACE);
  }
}


sub disorder_start_html {
  return start_html(
		 -title=>'DRIP-PRED - submission page',
		 -meta=>{keywords=>'protein structure prediction, disordered regions',
			 description=>'given an amino acid sequence, predicts regions without well-defined 3D structure'},
		 -head=>Link({-rel=>'stylesheet',
			      -type=>'text/css',
			      -href=>'http://www.sbc.su.se/sbc.css'})
		   );
}

sub disorder_title {
  return h2("DRIP<font color='#888888'>PRED</font> - Submit sequence");
}
