#!/bin/bash
set -e

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

init_cfg=(
"export ZENTAO_ENV=zbox-linux    #一键安装包名称"
"export APACHE_HOST=127.0.0.1    #Apache服务IP"
"export APACHE_PORT=80           #Apache服务端口"
"export MYSQL_HOST=127.0.0.1     #MySQL服务IP"
"export MYSQL_PORT=3306          #MySQL服务端口"
"export MYSQL_PASS=123456        #MySQL服务密码"
"export MYSQL_SOCK=/opt/zbox/tmp/mysql/mysql.sock #MySQL服务Socket"
"export DEFAULT_USER=nobody      #默认用户"
"export DEFAULT_GROUP=nogroup    #默认用户组"
"export MYSQL_SERVICE=enabled    #启动MySQL服务"
"export CHECK_MYSQL=true         #检查MySQL数据"
"export APACHE_SERVICE=enabled   #启动Apache服务"
"export XXD_SERVICE=enabled      #启动喧喧服务"
"export ROADRUNNER_SERVICE=enabled #启动roadrunner服务"
"export REDIS_SERVICE=enabled    #启动Redis服务"
"export REDISCLI_AUTH=pass4Redis #Redis服务密码"
"export ZT_CACHE_ENABLE=true     #禅道启用缓存"
"export ZT_CACHE_DRIVER=redis    #禅道缓存驱动"
"export ZT_CACHE_SCOPE=private   #禅道缓存作用域"
"export ZT_CACHE_NAMESPACE=zentao #禅道缓存命名空间"
"export ZT_CACHE_LIFETIME=0       #禅道缓存有效期"
"export ZT_REDIS_HOST=127.0.0.1   #禅道Redis服务IP"
"export ZT_REDIS_PORT=6379        #禅道Redis服务端口"
"export ZT_REDIS_PASSWORD=pass4Redis #禅道Redis服务密码"
"export ZT_REDIS_SERIALIZER=igbinary #禅道Redis序列化方式"
"export PATH=$PATH:/opt/zbox/bin     #PATH路径"
)

###############################################################
# 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

# shellcheck disable=SC1091
. /opt/zbox/.env

# Default parameters
export aport=${APACHE_PORT:-80}
export mport=${MYSQL_PORT:-3306}
export rport=${ZT_REDIS_PORT:-6379}
export DEFAULT_USER=${DEFAULT_USER:-nobody}
export DEFAULT_GROUP=${DEFAULT_GROUP:-nogroup}
export MYSQL_PASS=${MYSQL_PASS:-123456}
export ZT_REDIS_PORT=${ZT_REDIS_PORT:-6379}
export MYSQL_SOCK=${MYSQL_SOCK:-/opt/zbox/tmp/mysql/mysql.sock}
export CHECK_MYSQL=${CHECK_MYSQL:-true}

# 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:,rport:

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
      ;;
    --rport )
      if ! [[ "$2" =~ ^[0-9]+$ ]] || [[ "$2" -lt 1 ]] || [[ "$2" -gt 65535 ]]; then
        echo "Invalid Redis port: '$2'"
        exit 1
      fi
      rport="$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" ]] && [[ "$rport" == "$ZT_REDIS_PORT" ]]; then
    info "Starting service with Apache port=$aport, MySQL port=$mport, Redis port=$rport..."
    control_mysql start
    control_redis start
    control_apache start
    control_xxd start
    control_rr start
    service_status
  else
    info "Starting service with custom port,Apache port=$aport, MySQL port=$mport, Redis port=$rport..."

    # 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 Redis port and restart the service
    if [ "$rport" != "$ZT_REDIS_PORT" ];then
      change_port "redis" "$rport" \
      && control_redis restart
    else
      control_redis start
    fi

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

    # start roadrunner
    control_rr start

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