#!/bin/bash  

# define resource
resource=hpo

# base directory
BASE_DIR="/data/projects/glygen/downloads/$resource"
mkdir -p "$BASE_DIR"
cd "$BASE_DIR"

# repository and files for download
REPO="obophenotype/human-phenotype-ontology"
FILES=("genes_to_disease.txt" "phenotype_to_genes.txt" "phenotype.hpoa" "genes_to_phenotype.txt")

# timestamped folder
new_dir=$(date +%Y_%m_%d)
mkdir -p "$new_dir"
cd "$new_dir"

# download files
for FILE in "${FILES[@]}"; do
    curl -f -L -o "$FILE" "https://github.com/$REPO/releases/latest/download/$FILE" || echo "$FILE not found"
    echo "Downloaded $FILE"
done

# convert genes_to_disease.txt to CSV
GTD_FILE="genes_to_disease.txt"
if [ -f "$GTD_FILE" ]; then
    tr '\t' ',' < "$GTD_FILE" > "${GTD_FILE%.txt}.csv"
    echo "Converted $GTD_FILE to ${GTD_FILE%.txt}.csv"
fi

# update folder permissions
chmod -R 775 "$BASE_DIR/$new_dir/"

# create symbolic link to latest
cd "$BASE_DIR"
rm -f current
ln -s "$new_dir" current

echo "Download Complete"
