# 
# Magisk script action.sh for the Magisk Module with OpenVPN
#
# The script starts the VPN if openvpn is not running. The script stops the VPN if the VPN is already running..
#
# The script uses the OpenVPN config file /etc/openvpn/default.ovpn.
#
# To use another OpenVPN config file create the file /sdcard/Documents/openvpvn.rc with the statement
#
#    OPENVPN_CONFIG_FILE="<fully_qualified_name_of_the_openvpn_config_file"
#
# -----------------------------------------------------------------------------
#
# History
#  12.02.2026 /bs
#     initial release
#


# ----------------------------------------------------------------------------

# default OpenVPN config file
#
OPENVPN_CONFIG_FILE="/etc/openvpn/default.ovpn"

# default log file
#
OPENVPN_LOG_FILE="/sdcard/Download/openvpn.log"

# additional parameter for OpenVPN
#
OPENVPN_PARAMETER=""

# run openvpn in the background if started without terminal
#
tty -s || OPENVPN_PARAMETER=" --daemon"

# time to wait for the VPN after starting it in seconds
#
WAIT_TIME=10

# user defined config file
#
USER_CONFIG_FILE="/sdcard/Documents/openvpn.rc"


# -----------------------------------------------------------------------------
#
# the environment variable MODPATH is only defined by Magisk for the script customize.sh
#
[ "${MODPATH}"x = ""x ] && MODPATH="${0%/*}"

MODULE_NAME="$( grep "^id=" ${MODPATH}/module.prop  | cut -f2 -d "=" )"
[ "${MODULE_NAME}"x = ""x ] && MODULE_NAME="unknown_magisk_module"

MODULE_VERSION="$( grep "^version=" ${MODPATH}/module.prop  | cut -f2 -d "=" )"

MODULE_DESC="${MODULE_NAME} ${MODULE_VERSION}"

# customize.sh is sourced in
# #
[ "$0"x = "sh"x ] && SCRIPT_NAME="customize.sh" || SCRIPT_NAME="${0##*/}"


# -----------------------------------------------------------------------------
# save the file handle for STDOUT to file handle 5 ( &5 is used in the function printMsg )
#
exec 5>&1

# ----------------------------------------------------------------------------
#
# printMsg - print a Message to the Magisk output windwo even if redirection of STDOUT to the logfile is enabled
# 
# Usage: printMsg [message]
#
function printMsg {
   echo "$*" >&5
}

# ----------------------------------------------------------------------------
#
# LogDebugMsg - print a Message if DEBUG_MODE is ${__TRUE}
# 
# Usage: LogDebugMsg [message]
#
function LogDebugMsg {
  if [ ${DEBUG_MODE} = ${__TRUE} ] ; then
    echo "$*"
  fi
}

# -----------------------------------------------------------------------------
# change either "0 = 1" to "0 = 0" in this script or create the file /data/local/tmp/debug to enable the debug output to the log file
#
if [ 0 = 1  -o -r /data/local/tmp/debug ] ; then
  LOGFILE="/data/local/tmp/${MODULE_NAME}_${SCRIPT_NAME}.log"

  printMsg  "----"
  printMsg  "Messages to STDOUT are now redirected to the log file 
  ${LOGFILE}"
  printMsg  "----"

  exec 1>"${LOGFILE}" 2>&1
  
  if [ -r /data/local/tmp/trace ] ; then
    set -x
    TRACE_MODE=${__TRUE}
  else
    TRACE_MODE=${__FALSE}    
  fi

  DEBUG_MODE=${__TRUE}   
else
  DEBUG_MODE=${__FALSE}     
  TRACE_MODE=${__FALSE}
fi


# -----------------------------------------------------------------------------

# directory for temporary files created by OpenVPN (/dev is mounted on a ramdisk in Android)
#
TMPDIR="/dev/tmp"

MODULE_PROP_FILE="${MODPATH}/module.prop"

if [ -r "${USER_CONFIG_FILE}" ] ; then
  echo "Reading the config file \"${USER_CONFIG_FILE}\" ..."
  source "${USER_CONFIG_FILE}"
  if [ $? -ne 0 ] ; then
    echo "ERROR: Error reading the config file \"${USER_CONFIG_FILE}\""
    exit 100
  fi
fi

# create the directory for temporary files
#
mkdir -p "${TMPDIR}"

echo
echo "Checking if OpenVPN is currently running ..."
CUR_OUTPUT="$( /data/adb/magisk/busybox ps -a | grep -v grep | grep "openvpn --config"  )"

if [ "${CUR_OUTPUT}"x != ""x ] ; then
  echo "OpenVPN is currently running"
  echo "${CUR_OUTPUT}"
  echo
  echo  "Now stopping OpenVPN ..."
  CUR_PID="$( echo "${CUR_OUTPUT}" | awk '{ print $1}' )"
  if [ "${CUR_PID}"x != ""x ] ; then
    kill ${CUR_PID}; sleep 1 ; ps -p ${CUR_PID} 2>/dev/null 1>/dev/null &&  kill -9 ${CUR_PID}
    sed -i -e "s/^description=.*/description=The VPN is not running; press the Action button to start the VPN/g"  "${MODULE_PROP_FILE}"
  fi
  echo 
  echo "Press the \"Action\" button again to start the OpenVPN"
else
  echo "OpenVPN is currently not running"
  echo "Now starting OpenVPN ..."
  
  echo "Using the OpenVPN config file "
  echo "  \"${OPENVPN_CONFIG_FILE}\" "
  if [ ! -r "${OPENVPN_CONFIG_FILE}" ] ; then
    echo "EROR: The OpenVPN config file \${OPENVPN_CONFIG_FILE\" does not exist"
  else

    VPN_SERVER="$( grep "^[[:space:]]*remote"  "${OPENVPN_CONFIG_FILE}" | awk '{ print $2" port "$3 }'  | tail -1 )"
    echo "Using the VPN server \"${VPN_SERVER}\" ..."
    openvpn --config "${OPENVPN_CONFIG_FILE}" --log "${OPENVPN_LOG_FILE}" ${OPENVPN_PARAMETER}
    echo
    echo "Waiting up to ${WAIT_TIME} seconds for the VPN ..."

    OK=1
    i=0
    while [ $i -lt ${WAIT_TIME} ]; do

      ps -ef | grep -v grep | grep openvpn >/dev/null
      if [ $? -eq 0 ] ; then
        ifconfig tun0 2>/dev/null | grep "inet addr:"  >/dev/null
        if [ $? -eq 0 ] ; then
          OK=0
          break
        fi
      fi 
      printf "."
      sleep 1
      let i=i+1
    done
    printf "\n"

    if [ ${OK} = 0 ] ; then 
      echo "The VPN is up after $i seconds"
      sed -i -e "s/^description=.*/description=The VPN using the server ${VPN_SERVER} is running; press the Action button to stop the VPN/g"  "${MODULE_PROP_FILE}"
    else
      echo "WARNING: OpenVPN started but not working"
      echo "The logfile used is \"${OPENVPN_LOG_FILE}\" "
      echo 
      cat "${OPENVPN_LOG_FILE}"
      /data/adb/magisk/busybox ps -a | grep -v grep | grep "openvpn --config"  >/dev/null
      if [ $? -eq 0 ]  ; then
        sed -i -e "s/^description=.*/description=The VPN using the server ${VPN_SERVER} is not working; press the Action button to stop the VPN/g"  "${MODULE_PROP_FILE}"
        echo
        echo "Press the \"Action\" button again to stop the OpenVPN"
      else
        sed -i -e "s/^description=.*/description=The VPN using the server ${VPN_SERVER} is not working; press the Action button to start the VPN/g"  "${MODULE_PROP_FILE}"
        echo
        echo "Press the \"Action\" button again to start the OpenVPN"
      fi
    fi
  fi
fi





