#!/bin/sh

#set -vx

LCFILE=$SYSROOT/etc/pki/ca-trust/ca-legacy.conf
LLINK=$SYSROOT/etc/pki/ca-trust/source/ca-bundle.legacy.crt
LDEFAULT=$SYSROOT/usr/share/pki/ca-trust-legacy/ca-bundle.legacy.default.crt
LDISABLE=$SYSROOT/usr/share/pki/ca-trust-legacy/ca-bundle.legacy.disable.crt

# calculate relative path between two absolute paths
rel_path() {
    local source="$1"
    local target="$2"

    # Normalize paths (remove double slashes and trailing slashes)
    source=$(echo "$source" | sed 's#//*#/#g' | sed 's#/$##')
    target=$(echo "$target" | sed 's#//*#/#g' | sed 's#/$##')

    local common_part="$source"
    local result=""

    while [[ "${target#$common_part}" == "${target}" ]]; do
        common_part="$(dirname "$common_part")"
        if [[ -z "$result" ]]; then
            result=".."
        else
            result="../$result"
        fi
    done

    if [[ "$common_part" == "/" ]]; then
        result="$result/${target#/}"
    else
        result="$result/${target#$common_part/}"
    fi

    # Remove any remaining double slashes
    result=$(echo "$result" | sed 's#//*#/#g')

    # If result is empty, it means source and target are the same
    if [[ -z "$result" ]]; then
        result="."
    fi

    echo "$result"
}


# An absent value, or any unexpected value, is treated as "default".
is_disabled()
{
    grep -i "^legacy *= *disable *$" $LCFILE >/dev/null 2>&1
}

do_check()
{
    is_disabled
    if [ $? -eq 0 ]; then
        echo "Legacy CAs are set to DISABLED in file $LCFILE (affects install/upgrade)"
        LEXPECT=$LDISABLE
    else
        echo "Legacy CAs are set to DEFAULT in file $LCFILE (affects install/upgrade)"
        LEXPECT=$LDEFAULT
    fi
    echo "Status of symbolic link $LLINK:"
    readlink -v $LLINK
}

do_install()
{
    is_disabled
    if [ $? -eq 0 ]; then
        # found, legacy is disabled
        rel_target=$(rel_path $(dirname $LLINK) $LDISABLE)
        ln -sf $rel_target $LLINK
    else
        # expression not found, legacy is set to default
        rel_target=$(rel_path $(dirname $LLINK) $LDEFAULT)
        ln -sf $rel_target $LLINK
    fi
}

do_default()
{
    sed -i 's/^legacy *=.*$/legacy=default/' $LCFILE
    do_install
    $SYSROOT/usr/bin/update-ca-trust
}

do_disable()
{
    sed -i 's/^legacy *=.*$/legacy=disable/' $LCFILE
    do_install
    $SYSROOT/usr/bin/update-ca-trust
}

do_help()
{
    echo "usage: $0 [check | default | disable | install]"
}

if [[ $# -eq 0 ]]; then
  # no parameters
  do_help
  exit $?
fi

if [[ "$1" = "install" ]]; then
  do_install
  exit $?
fi

if [[ "$1" = "default" ]]; then
  do_default
  exit $?
fi
if [[ "$1" = "disable" ]]; then
  do_disable
  exit $?
fi

if [[ "$1" = "check" ]]; then
  do_check
  exit $?
fi

echo "$0: Unsupported command $1"
do_help
