#!/bin/bash -x
#this script will try and delete a list of publications from Canto (one PMID per line in the file PMID_to_delete.tsv)
## if publications have associated sessions (which all loaded publications in flybase-vm's Canto should have by default... unless sessions are manulally deleted), publications cannot be deleted. Therefore, the script will a) try to delete the publications, b) any existing sessions will be listed in "sessions_to_delete.txt", c) which will then be deleted, and c) finally the original list of publications will be deleted.

FILENAME="PMID_to_delete.tsv"

# this will delete publications any publications without sessions; if sessions exist, the curs_key/ID will be spelled out in the output, written into "temp_output.txt"
sudo ./canto/script/canto_docker ./script/canto_delete.pl --pub $(cat "${FILENAME}") > "temp_output.txt"

# curs_key will appear in a line after a double white-space
# To retrieve curs_keys and eliminate the white spaces, run:
sed -n -e '/  /p' "temp_output.txt" > "temp_output1.txt"
sed 's/  //' "temp_output1.txt" > "temp_output2.txt"

#this will replace the odd character '/r' with a white-space and write the sessions list into the file "sessions_to_delete.txt"
# ('/r' characters would prevent sessions from being deleted, therefore they need to be deleted)
FILENAME1="temp_output2.txt"
SESS_DEL=$(cat "${FILENAME1}")
echo ${SESS_DEL} | tr '\r' ' ' > "sessions_to_delete.txt"

#the following lines will a) 1st remove all sessions and b) repeat the command to delete the original list of publications
FILENAME2="sessions_to_delete.txt"
sudo ./canto/script/canto_docker ./script/canto_delete.pl --curs $(cat "${FILENAME2}")
sudo ./canto/script/canto_docker ./script/canto_delete.pl --pub $(cat "${FILENAME}")

rm "temp_output.txt"
rm "temp_output1.txt"
rm "temp_output2.txt"
rm "sessions_to_delete.txt"
