#!/bin/bash
# CC0: The author hereby waives all copyright and related or neighboring rights
# together with all associated claims and causes of action with respect to this
# work to the extent possible under the law.

app_description='
NAME
    cacert_replace.sh

SYNOPSIS
    cacert_replace.sh [options]

DESCRIPTION
    cacert_replace.sh searches the directory tree of hscPipe
    for files named "cacert.pem" and "cert.pem",
    and replaces these files with symlinks to "cert.pem" provided by the OS.
    It thereby gets rid of certificate lists possibly polluted with eMudhra.

OPTIONS
    --ca-cert=FILE
        CA certificate list provided by the OS,
        which is by default obtained by calling "openssl" command.
    --hscpipe-dir=DIR
        Specify the top directory of hscPipe,
        which is by default guessed from environment variables.
    -y, --yes
        Answer yes to all questions.
    -h, --help
        Show this message and exit.
'

# openssl's absolute path.
# It must be absolute for fear that non-OS openssl may be selected.
openssl=/usr/bin/openssl


main()
{
    set -e

    local hscpipe_dir=""
    local ca_cert=""
    local yes=""

    while [ "$#" -gt 0 ]
    do
        case "$1" in
        "--ca-cert" )
            shift
            ca_cert="$(get_option_arg --ca-cert "$@")"
            ;;
        "--ca-cert="* )
            ca_cert="${1#--ca-cert=}"
            ;;
        "--hscpipe-dir" )
            shift
            hscpipe_dir="$(get_option_arg --hscpipe-dir "$@")"
            ;;
        "--hscpipe-dir="* )
            hscpipe_dir="${1#--hscpipe-dir=}"
            ;;
        "-y" | "--yes" )
            yes="y"
            ;;
        "-h" | "--h" | "--he" | "--hel" | "--help" )
            show_help
            return 0
            ;;
        "--" )
            shift
            break
            ;;
        "-"?* )
            print_error "invalid option: $1"
            return 1
            ;;
        * )
            print_error "invalid argument: $1"
            return 1
            ;;
        esac
        shift
    done

    if [ "$#" -gt 0 ]
    then
        print_error "invalid argument: $*"
        return 1
    fi

    if [ x"${hscpipe_dir}" = x"" ]
    then
        hscpipe_dir="$(find_hscpipe_dir)"
    else
        hscpipe_dir="$(realpath -s "${hscpipe_dir}")"
    fi

    if [ x"${ca_cert}" = x"" ]
    then
        ca_cert="$(find_system_ca)"
    else
        ca_cert="$(realpath -s "${ca_cert}")"
    fi

    echo "Searching '${hscpipe_dir}' for (ca)cert.pem ..."

    local certlist
    certlist="$(mktemp)"

    find_cacerts "${hscpipe_dir}" > "${certlist}"

    if ! [ -s "${certlist}" ]
    then
        print_error "no (ca)cert.pem was found."
        return 1
    fi

    echo "Found (ca)cert.pem:"
    cat "${certlist}"

    echo "All the files above will be replaced with symlinks to"
    echo "    '${ca_cert}'."

    if [ x"${yes}" = x"" ]
    then
        local reply=
        read -p "Is that OK? [y/N]" reply
        case "${reply}" in
        [yY] | [yY][eE][sS] )
            ;;
        * )
            print_error "cancelled."
            return 1
        esac
    fi

    replace_cacerts "${ca_cert}" < "${certlist}"

    rm "${certlist}"
    echo "Done."
}


find_cacerts()
{
    set -e

    local dirname="$1"

    find "${dirname}" \( -name "cert.pem" -o -name "cacert.pem" \) -print
}


find_hscpipe_dir()
{
    set -e

    if [ x"${OBS_SUBARU_DIR}" == x"" ]
    then
        print_error 'set up hscPipe before running this program.'
        return 1
    fi

    local dir=
    # hscPipe8
    dir="${OBS_SUBARU_DIR%/lsst_home/*}"
    if [ x"${dir}" != x"${OBS_SUBARU_DIR}" ]
    then
        echo "${dir}"
        return 0
    fi
    # lsst stack v24
    dir="${OBS_SUBARU_DIR%/conda/envs/*}"
    if [ x"${dir}" != x"${OBS_SUBARU_DIR}" ]
    then
        echo "${dir}"
        return 0
    fi

    print_error "failed to guess pipeline directory (use --hscpipe-dir=DIR)."
    return 1
}


find_system_ca()
{
    set -e

    local openssldir
    openssldir="$("${openssl}" version -d | { read key value && echo "${value}" ; } )"
    openssldir="${openssldir%[\"\']}"
    openssldir="${openssldir#[\"\']}"

    local system_ca
    system_ca="${openssldir}/cert.pem"

    if ! [ -e "${system_ca}" ]
    then
        print_error "${system_ca} does not exist."
        return 1
    fi

    echo "${system_ca}"
}


get_option_arg()
{
    set -e

    local option_name="$1"
    shift

    if ! [ "$#" -gt 0 ]
    then
        print_error "option ${option_name} requires an argument."
        return 1
    fi

    case "$1" in
    "-"?* )
        print_error "option ${option_name} requires an argument."
        return 1
    esac

    echo "$1"
}


print_error()
{
    echo "error:" "$@" >&2
    return 1
}


replace_cacerts()
{
    set -e

    local target="$1"

    local name
    while IFS= read -r name
    do
        if ! [ -e "${name}" ]
        then
            print_error "file '${name}' does not exist." || true
            continue
        fi
        ln -s -f "${target}" "${name}" || true
    done
}


show_help()
{
    echo -n "${app_description#?}"
}


main "$@"
