#!/bin/bash
set -e

init_cfg=(
"export ZENTAO_ENV=zbox-linux"
"export APACHE_HOST=127.0.0.1"
"export APACHE_PORT=80"
"export MYSQL_HOST=127.0.0.1"
"export MYSQL_PORT=3306"
"export MYSQL_PASS=123456"
"export DEFAULT_USER=nobody"
"export DEFAULT_GROUP=nogroup"
"export MYSQL_SERVICE=enabled"
"export APACHE_SERVICE=enabled"
"export XXD_SERVICE=enabled"
"export ROADRUNNER_SERVICE=enabled"
"export PATH=$PATH:/opt/zbox/bin"
)

###############################################################
# Function: init_env
# Description: Initialize default configuration file
# Arguments: None
# Returns: None
###############################################################
function init_env(){
  [ ! -f /opt/zbox/.env ] && touch /opt/zbox/.env

  for cfg in "${init_cfg[@]}"
  do
      cfg_name=${cfg%%=*}

      if [ "$(awk "/$cfg_name/" /opt/zbox/.env)" == "" ];then
       echo "$cfg" >> /opt/zbox/.env
      fi
  done
}

init_env

# Import default configuration
# shellcheck disable=SC1091
. /opt/zbox/.env

# Default parameters
export aport=${APACHE_PORT:-80}
export mport=${MYSQL_PORT:-3306}
export DEFAULT_USER=${DEFAULT_USER:-nobody}
export DEFAULT_GROUP=${DEFAULT_GROUP:-nogroup}
export MYSQL_PASS=${MYSQL_PASS:-123456}

# shellcheck disable=SC1091
. /opt/zbox/bin/lib/libcomm.sh

basePath=$(dirname "$(readlink -f "$0")")

# Check the running directory
check_basePath "$basePath"

# Parse command line arguments
LONGOPTS=aport:,mport:

PARSED=$(getopt --longoptions=$LONGOPTS --name "$0" -o '' -- "$@")
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
  exit 1
fi

eval set -- "$PARSED"

while true; do
  case "$1" in
    --aport)
      if ! [[ "$2" =~ ^[0-9]+$ ]] || [[ "$2" -lt 1 ]] || [[ "$2" -gt 65535 ]]; then
        echo "Invalid Apache port: '$2'"
        exit 1
      fi
      aport="$2"
      shift 2
      ;;
    --mport )
      if ! [[ "$2" =~ ^[0-9]+$ ]] || [[ "$2" -lt 1 ]] || [[ "$2" -gt 65535 ]]; then
        echo "Invalid MySQL port: '$2'"
        exit 1
      fi
      mport="$2"
      shift 2
      ;;
    --)
      shift
      break
      ;;
    *)
      echo "Invalid option: '$1'"
      exit 1
      ;;
  esac
done

#  If it is the start command and no port number is specified, use the default value
command=${1,,}

if [[ "$command" == "start" ]]; then

  # Check the user and group
  check_user_group "$DEFAULT_USER" "$DEFAULT_GROUP"

  # Check directory permissions
  check_permission "$DEFAULT_USER" "$DEFAULT_GROUP"
  
  if [[ "$aport" == "$APACHE_PORT" ]] && [[ "$mport" == "$MYSQL_PORT" ]]; then
    info "Starting service with Apache port=$aport, MySQL port=$mport..."
    control_mysql start
    control_apache start "$aport"
    control_xxd start
    control_rr start
    service_status
  else
    info "Starting service with custom port,Apache port=$aport, MySQL port=$mport..."

    # Adjust the MySQL port and restart the service
    if [ "$mport" != "$MYSQL_PORT" ];then
      change_port "mysql" "$mport" \
      && control_mysql restart 
    else
      control_mysql start
    fi

    # Adjust the Apache port and restart the service
    if [ "$aport" != "$APACHE_PORT" ];then
      change_port "apache" "$aport" \
      && control_apache restart "$aport" \
      && control_xxd restart
    else
      control_apache start "$aport"\
      && control_xxd start
    fi

    # start roadrunner
    control_rr start
    service_status
  fi
else
  # Execute other commands
  case "$command" in
    stop)
      control_apache stop
      control_xxd stop
      control_mysql stop
      control_rr stop
      service_status
      ;;
    status)
      info "Checking service status..."
      service_status
      ;;
    restart)
      control_apache restart "$aport"
      control_mysql restart
      control_xxd restart
      control_rr restart
      service_status
      ;;
    "check")
      info "Check service status based on .env configuration..."
      control_apache check "$aport"
      control_mysql check
      control_xxd check
      control_rr check
      service_status
      ;;
    *)
      echo "Usage: $0 {start|stop|status|check} [--aport=8080] [--mport=3307]" >&2
      exit 1
      ;;
  esac
fi