#!/bin/bash

#INPUT
#  INPUT INPUT
#### 2. name of .pdb file. Do not include .pdb extension in the name.
sysname=sym2_den


#################################
##################################
module load gromacs
module load python2

#This uses martini v2.2 forcefield

# dsspcmbi needs some permissions to be run by martinize.py
chmod +x dsspcmbi

# 1. Generate coarse grained topology for protein
rm $sysname'.top'
python martinize.py -f $sysname'.pdb' -o $sysname'.top' -x $sysname'-cg.pdb' -dssp ./dsspcmbi -p backbone -ff martini22

# 2.Create the periodic box (no solvent yet)
gmx_mpi editconf -f $sysname'-cg.pdb' -d 1.0 -bt cubic -o $sysname'-cg.gro'

# 3. Create our run input file to minimize our vacuum system
gmx_mpi grompp -p $sysname'.top' -f minimize.mdp -c $sysname'-cg.gro' -o vacuum-minimized.tpr

# 4. Quick Minimize (not sure if required)
gmx_mpi mdrun -deffnm vacuum-minimized -v

# 5. Add solvent box to minimized system
# 5a. For older gromacs use this line:
# gmx_mpi genbox -cp vacuum-minimized.gro -cs water.gro -vdwd 0.21 -o solvated.gro -p $sysname'.top'
# 5b. For newer gromacs use this line:
gmx_mpi solvate -cp vacuum-minimized.gro -cs water.gro -radius 0.21 -o solvated.gro -p $sysname'.top'
# Edit the end of the $sysname'.top file to reflect the number of waters added in step 5.
nWaters=$(grep -c W solvated.gro)
echo $'\nW    '$nWaters >> $sysname'.top'

# 6. Add ions by replacing solvent waters (group 13) by ions in a random fashion.
# Combine files for our solvated system (need to do this to allow ionization later)
gmx_mpi grompp -p $sysname'.top' -f minimize.mdp -c solvated.gro -o solvated.tpr
# The '13' is just to choose which group of atoms (e.g. backbone, calphas, solvent) to randomly replace with ions. In almost all cases we want to replace solvent
printf '13' | gmx_mpi genion -s solvated.tpr -o ionized.gro -p $sysname'.top' -neutral
# Edit the beginning of the $sysname'.top file to include topologies for the ions we added before.
# Note: the #include "martini-ions.itp" line needs to come after the "#include martini.itp" line in the file. Hence the '2s' after sed to indicate second line.
sed -i '2s/^/#include "martini-ions.itp"\n/' $sysname'.top'

# 7. Combine files again
gmx_mpi grompp -p $sysname'.top' -c ionized.gro -f minimize.mdp -o ionized-minimized.tpr

# 8. Minimize the solvated and ionized system
gmx_mpi mdrun -deffnm ionized-minimized -v

# 9. Prepare/Combine files for equilibration
gmx_mpi grompp -p $sysname'.top' -c ionized-minimized.gro -f equilibration.mdp -o equilibrate.tpr

# 10. Run Equilibration
gmx_mpi mdrun -deffnm equilibrate

#11. Prepare/Combine files for MD
gmx_mpi grompp -p $sysname'.top' -c equilibrate.gro -r equilibrate.gro -f MD.mdp -o MD.tpr -maxwarn 1
