#!/bin/bash

# check if squid is using 8080, if yes, then move to 8081
intercept=$(/usr/sbin/e-smith/config getprop squid InterceptPort||echo "8080")
squidstatus=$(/usr/sbin/e-smith/config getprop squid status||echo "disabled")

if [[ "$intercept" == "8080" && "$squidstatus" == "enabled" ]]; then
 echo "we set squid Intercept port to 8081.. to avoid conflict with unifi "
 /usr/sbin/e-smith/config setprop squid InterceptPort 8081
 /usr/sbin/e-smith/expand-template /etc/squid/squid.conf
 /usr/sbin/e-smith/expand-template /etc/rc.d/init.d/masq 
 /usr/bin/systemctl restart squid
 /usr/bin/systemctl restart masq

fi

# now deal with dansguardian
dport=$(/usr/sbin/e-smith/config getprop dansguardian port ||echo "8080")
dstatus=$(/usr/sbin/e-smith/config getprop dansguardian status||echo "disabled")
if [[ "$dport" == "8080" && "$dsatus" == "enabled" ]]; then
 echo "we set dansguardian port to 8081.. to avoid conflict with unifi "
  /usr/sbin/e-smith/config setprop dansguardian port 8081
  /usr/sbin/e-smith/expand-template /etc/dansguardian/dansguardian.conf 
  /usr/bin/systemctl restart dansguardian
fi

# nothing to do with with squidguard

# set java 21 
JAVA_VERSION="21"
RPM_JDK_PATH="/usr/lib/jvm/$(rpm -q java-${JAVA_VERSION}-openjdk 2>/dev/null)/bin/java"
RPM_JRE_PATH="/usr/lib/jvm/$(rpm -q jre-${JAVA_VERSION}-openjdk 2>/dev/null)/bin/java"
STATIC_JDK_PATH="/usr/lib/jvm/java-${JAVA_VERSION}-openjdk/bin/java"
STATIC_JRE_PATH="/usr/lib/jvm/jre-${JAVA_VERSION}-openjdk/bin/java"
IS_SUCCESSFUL=false
for target_path in "$RPM_JDK_PATH" "$RPM_JRE_PATH" "$STATIC_JDK_PATH" "$STATIC_JRE_PATH"; do
    # Skip empty or malformed paths if the rpm query failed
    if [[ -z "$target_path" || "$target_path" == "/usr/lib/jvm//bin/java" ]]; then
        continue
    fi

    # -x checks if the file exists and is executable
    if [ -x "$target_path" ]; then
        #echo "Valid Java path found for version ${JAVA_VERSION}: $target_path"
        /usr/sbin/alternatives --set java "$target_path"
        IS_SUCCESSFUL=true
        break # Exit the loop immediately after the first match
    fi
done
if [ "$IS_SUCCESSFUL" = false ]; then
    echo "Error: No valid JDK or JRE path found for Java ${JAVA_VERSION}." >&2
fi

exit 0
