#!/bin/bash  

# define resource
resource=glytoucan
resource2=glycan_list

# add the time_stamped_folders
cd /data/projects/glygen/downloads/$resource/

new_dir=$(date +%Y_%m_%d)
mkdir $new_dir && echo "Created new directory /data/projects/glygen/downloads/$resource/$new_dir"
mkdir /data/projects/glygen/downloads/$resource2/$new_dir && echo "Created new directory /data/projects/glygen/downloads/$resource2/$new_dir"

# download files to new folder
cd /data/projects/glygen/downloads/$resource/$new_dir
wget https://github.com/glygen-glycan-data/PyGly/archive/refs/tags/GlyGen-GlycanData-Export-Current.zip 

# unzip export folder
echo "Unzipping export..."
unzip GlyGen-GlycanData-Export-Current.zip

# move export folder to downloads, delete unused PyGly directory
mv PyGly-GlyGen-GlycanData-Export-Current/smw/glycandata/export/ /data/shared/glygen/downloads/$resource/$new_dir/
mv PyGly-GlyGen-GlycanData-Export-Current/smw/glycandata/data/glytoucan_allacc.txt /data/shared/glygen/downloads/$resource2/$new_dir/
mv PyGly-GlyGen-GlycanData-Export-Current/smw/glycandata/data/glytoucan_archived.txt /data/shared/glygen/downloads/$resource2/$new_dir/
mv PyGly-GlyGen-GlycanData-Export-Current/smw/glycandata/data/glytoucan_replaced.txt /data/shared/glygen/downloads/$resource2/$new_dir/

rm -rf PyGly-GlyGen-GlycanData-Export-Current/
rm -rf GlyGen-GlycanData-Export-Current.zip

# run unzip.sh program in new export folder
cd /data/shared/glygen/downloads/$resource/$new_dir/export/ && bash /software/glygen/legacy/unzip.sh 

# run glycan_images.sh program in new export folder
cd /data/shared/glygen/downloads/$resource/$new_dir/export/ && bash /software/glygen/legacy/glycan_images.sh

# prepare glycoctxml files
echo "Preparing glycoctxml files..."
cd /data/shared/glygen/downloads/$resource/$new_dir/export/
mkdir glycoctxml
cat glycoctxml.zip.* > glycoctxml/glycoctxml_all.zip || {
    echo "Error unzipping glycoctxml_all.zip, try excluding glycoctxml.zip.04 file"
    exit 1
}

cd glycoctxml
unzip glycoctxml_all.zip

# update new folder permissions
chmod -R 775 /data/shared/glygen/downloads/$resource/$new_dir/
chmod -R 775 /data/shared/glygen/downloads/$resource2/$new_dir/

# create symbolic link
cd /data/projects/glygen/downloads/$resource/
rm current
ln -s $new_dir current

cd /data/projects/glygen/downloads/$resource2/
rm current
ln -s $new_dir current
