import os

rule check_md5_of_direct_dl:
    input:
        file_to_check="{db_dir}/direct_dl/{filename}",
        md5_file="{db_dir}/direct_dl/{filename}.md5"
    output:
        "{db_dir}/processed/{filename}.md5.checked"
    params:
        dl_dir = lambda w, input: os.path.dirname(input.md5_file),
        md5_file_rel = lambda w, input: os.path.basename(input.md5_file)
    shell:
        """
        CURRENT_DIR=$(pwd)
        cd {params.dl_dir}
        set +e
        md5sum -c --quiet {params.md5_file_rel}
        MD5SUCCESS=$?
        set -e
        if [[ $MD5SUCCESS -eq 0 ]]; then
          cd $CURRENT_DIR
          touch {output[0]}
        else
          echo "Wrong checksum for file '{input.file_to_check}'."
          echo "Please delete and rerun"
          exit 1
        fi
        """