#!/bin/sh

# BEGIN DESCRIPTION
# SYNOPSYS
#     $program [DIR]
#
# DESCRIPTION
#     This program patches hscpipe 8.x so that it won't violate the limit on
#     the number of open files.
#
#     For example, if you see such an error message as
#     \"sqlite3.OperationalError: unable to open database file\"
#     after the pipeline normally runs for a while,
#     then the real cause of the failure is probably that the pipeline
#     opens too many files, and the problem can probably be fixed
#     by this program.
#
#     If hscpipe 8.x has been set up (or to be specific, if \$DAF_PERSISTENCE_DIR
#     has been set), DIR can be omitted.
#     If DIR is specified, it must be the path to hscpipe 8.x. For example,
#
#         $program /opt/hscpipe/8.4
# END DESCRIPTION

if [ "$1" = "-h" ] || [ "$1" = "--help" ]
then
    program=$(basename "$0")
    eval echo \""$(
        sed -n -e '/^# BEGIN DESCRIPTION/,/^# END DESCRIPTION/{s/^\(# \|#\)//;p}' "$0" |
        sed -n -e '1d;$d;p'
    )"\"

    exit 0
fi

if [ "$#" -eq 0 ] && [ -z "$DAF_PERSISTENCE_DIR" ]
then
    echo "Please setup hscpipe 8.x first,"
    echo "or specify where hscpipe 8.x has been installed."
    echo ""
    echo "See --help."
    exit 1
fi

if [ "$#" -gt 1 ]
then
    shift
    echo "error: Unrecognized arguments:" "$@"
    echo ""
    echo "See --help."
    exit 1
fi

if [ "$#" -eq 1 ]
then
    echo "Searching $1 for 'daf_persistence' installation ..."
    found="$(find "$1" -type d -name "ups" -path "*/daf_persistence/*/ups")"

    if [ -z "$found" ]
    then
        echo "error: Directory 'daf_persistence' is not found."
        exit 1
    fi
    if [ "$(echo "$found" | wc -l)" -ne 1 ]
    then
        echo "error: More than one 'daf_persistence' installation are found:"
        echo "$found"
        exit 1
    fi

    DAF_PERSISTENCE_DIR="$(dirname "$found")"
    echo "Found DAF_PERSISTENCE_DIR=$DAF_PERSISTENCE_DIR"
fi

if ! cd "$DAF_PERSISTENCE_DIR"
then
    echo "error: Cannot change directory to: \$DAF_PERSISTENCE_DIR=$DAF_PERSISTENCE_DIR"
    exit 1
fi

checksum="$(cksum python/lsst/daf/persistence/registries.py)"

# Not patched
if [ "$checksum" != "3527081927 19557 python/lsst/daf/persistence/registries.py" ]
then
    echo "warning: File checksum indicates $DAF_PERSISTENCE_DIR has already been modified."
    echo "Applying patches to this directory may mess it up. Proceed anyway?"
    answer="n"
    read -p "[y/N]" answer
    if [ -z "$(echo "$answer" | grep '^y')" ]
    then
        echo "Canceled."
        exit 1
    fi
fi

echo "Applying patches to $DAF_PERSISTENCE_DIR..."

patch -p0 << "__end_of_patch__"
--- python/lsst/daf/persistence/registries.py	2021-11-18 13:35:25.000000000 +0900
+++ python/lsst/daf/persistence/registries.py	2023-02-09 11:00:26.683434210 +0900
@@ -34,6 +34,7 @@
 """
 import copy
 from . import fsScanner, sequencify
+import functools
 import os
 import astropy.io.fits
 import re
@@ -72,7 +73,11 @@
         """Create a registry object of an appropriate type.
         @param location (string) Path or URL for registry, or None if
                                  unavailable"""
+        return Registry.__create(location, os.getpid())

+    @staticmethod
+    @functools.lru_cache(maxsize=None)
+    def __create(location, pid):
         if location is None:
             return

__end_of_patch__
