#!/bin/bash

wfc_work_dir=/opt/wfc
docker_work_dir=${wfc_work_dir}/docker
redis_work_dir=${docker_work_dir}/redis
src_service_dir=${wfc_work_dir}/systemd/system
dst_service_dir=/etc/systemd/system
java_work_dir=${docker_work_dir}/java
ssl_work_dir=${docker_work_dir}/nginx/ssl

base_dockers="wfc-nacos wfc-mysql wfc-redis"
jar_dockers="wfc-auth wfc-gateway wfc-modules-system wfc-modules-user wfc-modules-job wfc-modules-file wfc-modules-payment"
modules_dockers="wfc-modules-system wfc-modules-user wfc-modules-job wfc-modules-file wfc-modules-payment"
fe_docker=wfc-nginx

docker_mysql_conf_d=/etc/mysql/conf.d
docker_my_conf_file=${docker_mysql_conf_d}/my.cnf

wfc_jar_images=$(docker images --format "{{.Repository}}"|grep -E "docker-wfc-|docker_wfc-")
wfc_modules_images=$(docker images --format "{{.Repository}}"|grep -E "docker-wfc-modules-|docker_wfc-modules-")

conf_dirs=" ${docker_work_dir}/conf
            ${docker_work_dir}/redis/conf
            ${docker_work_dir}/mysql/conf.d
            ${docker_work_dir}/nacos/conf
            ${docker_work_dir}/nginx/conf            
            ${docker_work_dir}/wfc/gateway/conf
            ${docker_work_dir}/wfc/auth/conf
            ${docker_work_dir}/wfc/modules/system/conf 
            ${docker_work_dir}/wfc/modules/user/conf 
            ${docker_work_dir}/wfc/modules/job/conf 
            ${docker_work_dir}/wfc/modules/file/conf 
            ${docker_work_dir}/wfc/modules/payment/conf
            "
case "$1" in
    env)
        # prepare directory
        mkdir -p ${docker_work_dir}/mysql/tmp
        chown -R root:root ${docker_work_dir}
        if [ ! -d ${redis_work_dir}/data ]; then
            mkdir -p ${redis_work_dir}/data
        fi

        # setup system serivce 
        if [ -f ${src_service_dir}/wfccontrol.service ]; then
            cp -rf ${src_service_dir}/wfccontrol.service ${dst_service_dir}/
            systemctl daemon-reload
            systemctl enable wfccontrol.service
        fi

       if [ ! -f ${docker_work_dir}/docker-compose.yml ]; then
            cp ${docker_work_dir}/compose/docker-compose.yml ${docker_work_dir}/docker-compose.yml
       fi

        # 获取传入的IP地址
        new_ip=$2

        # env定义原始文件和临时文件
        def_env_file=${docker_work_dir}/env/default.env
        org_env_file=${docker_work_dir}/.env
        tmp_env_file=${docker_work_dir}/temp.env

        if [ ! -f ${org_env_file} ]; then
            cp ${def_env_file} ${org_env_file}
        fi

        # copy default config files to conf directory
        for conf_dir in $conf_dirs; do
            if [ ! -d $conf_dir ]; then
                continue
            fi
            if [ ! -d $conf_dir/default ]; then
                continue
            fi            
            # 遍历config default配置文件
            for file in "$conf_dir/default"/*; do
                filename=$(basename "$file")

                # 如果conf目录下不存在相应的文件，则拷贝
                if [ ! -f "$conf_dir/$filename" ]; then
                    cp -rf "$file" "$conf_dir/"
                fi
            done
        done


        if [ ! -z "${new_ip}" ]; then
            # 使用sed命令替换IP地址
            # 替换.env文件
            sed "s/WFC_SERVER_IP=.*/WFC_SERVER_IP=${new_ip}/" ${org_env_file} > $tmp_env_file
            mv $tmp_env_file $org_env_file 
        fi

        # Check system timezone
        if [ -f /etc/timezone ]; then
            TIMEZONE=$(cat /etc/timezone)
        elif [ -f /etc/localtime ]; then
            TIMEZONE=$(readlink /etc/localtime | sed 's|.*/zoneinfo/||')
        else
            TIMEZONE="UTC"
        fi
        if grep -q "TZ=" ${org_env_file}; then
            sed "s|TZ=.*|TZ=${TIMEZONE}|" ${org_env_file} > $tmp_env_file
            mv $tmp_env_file $org_env_file 
        else
            echo "TZ=${TIMEZONE}" >> ${org_env_file}
        fi
                
        # replace nginx.conf gateway server ip and port

        while IFS= read -r line; do
            if [[ ! $line =~ ^# && $line =~ .*=.* ]]; then
                eval "export $line"
            fi
        done < $org_env_file

        # 生成ssl证书
        # openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout ${ssl_work_dir}/server.key -out ${ssl_work_dir}/server.crt -config ${ssl_work_dir}/req.cnf -sha256

        # nginx定义原始文件和临时文件
        org_nginx_conf=${docker_work_dir}/nginx/conf/nginx.conf
        tmp_intermediate_conf=${docker_work_dir}/nginx/conf/tmp_intermediate.conf
        tmp_nginx_conf=${docker_work_dir}/nginx/conf/tmp_nginx.conf

        # 使用sed命令替换proxy_pass行中的IP地址
        # Define intermediate temporary nginx configuration file
        # Replace the proxy_pass line with the correct GATEWAY_SERVER_IP and GATEWAY_SERVER_PORT
        sed "s|proxy_pass http://.*:8080/;|proxy_pass http://${GATEWAY_SERVER_IP}:${GATEWAY_SERVER_PORT}/;|" $org_nginx_conf > $tmp_intermediate_conf

        # Replace the IP address and port for the file server in the nginx configuration
        sed "s|proxy_pass http://.*:9201/;|proxy_pass http://${GATEWAY_SERVER_IP}:${WFC_FILE_PORT}/;|" $tmp_intermediate_conf > $tmp_nginx_conf

        # Remove the intermediate temporary file and move the final configuration
        rm $tmp_intermediate_conf
        mv $tmp_nginx_conf $org_nginx_conf

        # 统一替换系统名
        nginx_html_u_zh=${docker_work_dir}/nginx/html/dist/u/langs/zh-cn.js
        nginx_html_u_en=${docker_work_dir}/nginx/html/dist/u/langs/en-us.js
        nginx_html_sys_zh=${docker_work_dir}/nginx/html/dist/sys/langs/zh-cn.js
        nginx_html_sys_en=${docker_work_dir}/nginx/html/dist/sys/langs/en-us.js
        sed -i "3s|title: '.*'|title: '${SYSTEM_TITLE}'|" $nginx_html_u_zh
        sed -i "3s|title: '.*'|title: '${SYSTEM_TITLE}'|" $nginx_html_u_en
        sed -i "3s|title: '.*'|title: '${SYSTEM_TITLE}'|" $nginx_html_sys_zh
        sed -i "3s|title: '.*'|title: '${SYSTEM_TITLE}'|" $nginx_html_sys_en

        # chown and chmod for all docker work directory
        if [ -d ${docker_work_dir}/mysql/data ]; then
            chown -R 999:999 ${docker_work_dir}/mysql/data
        fi
        find ${docker_work_dir} -type d -exec chmod 775 {} \;
        find ${docker_work_dir} -type f -exec chmod 664 {} \;
        chown root:root ${docker_work_dir}/mysql/conf.d/my.cnf
        chmod 600 ${docker_work_dir}/mysql/conf.d/my.cnf
        chmod 1777 ${docker_work_dir}/mysql/tmp
        ;;
    initdb)
        # init database
        cd ${docker_work_dir}
        docker-compose up -d wfc-mysql
        sleep 10
        for sql in ${docker_work_dir}/mysql/db/*.sql; do
            if [ -f "$sql" ]; then
                echo -n "Execute SQL script: ${sql} ... "
                docker exec -i wfc-mysql mysql --defaults-extra-file=${docker_my_conf_file} < ${sql}
                if [ $? = 0 ]; then
                    echo "done" 
                fi
            else
                echo "No SQL files found in ${docker_work_dir}/mysql/db/"
            fi
        done
        ;;
    upgdb)
        mysql_container_name=wfc-mysql
        # upgrade database
        cd ${docker_work_dir}
        docker-compose up -d ${mysql_container_name}    
        sleep 10
        # 获取 MySQL 容器的 IP 地址和端口
        mysql_container_ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${mysql_container_name})
        mysql_container_port=$(docker inspect -f '{{(index (index .NetworkSettings.Ports "3306/tcp") 0).HostPort}}' ${mysql_container_name})

        # 在容器内生成 my.cnf 文件
        docker exec ${mysql_container_name} bash -c "cat <<EOF > ${docker_my_conf_file}
[client]
user=root
password=\${MYSQL_ROOT_PASSWORD}
host=wfc-mysql
port=${mysql_container_port}
EOF"

        # 检查容器健康状态
        timeout=60
        interval=2
        elapsed=0
        while [ $elapsed -lt $timeout ]; do
            health_status=$(docker inspect --format='{{.State.Health.Status}}' $mysql_container_name)
            if [ "$health_status" == "healthy" ]; then
                echo "Container $mysql_container_name is healthy"
                echo "Executing database upgrade scripts ..."
                ${wfc_work_dir}/bin/wfcupgrade.sh
                exit 0
            fi
            sleep $interval
            elapsed=$((elapsed + interval))
        done

        echo "Container $mysql_container_name is not healthy after $timeout seconds, please check the container status."
        ;;          
    base)
        # build docker compose
        cd ${docker_work_dir}
        docker-compose stop ${base_dockers}
        docker-compose build ${base_dockers}   
        cd ${java_work_dir}
        if [[ "$(docker images -q wfc-java:jre8 2> /dev/null)" == "" ]]; then
            echo "Building wfc-java:jre8"
            docker build -t wfc-java:jre8 -f dockerfile .
        fi        
        ;;
    jar)
        # build docker compose
        cd ${docker_work_dir}
        docker-compose stop ${jar_dockers}
        docker-compose build ${jar_dockers}
        ;;
    modules)
        # build docker compose
        cd ${docker_work_dir}
        docker-compose stop ${modules_dockers}
        docker-compose build ${modules_dockers}  
        ;;
    fe)
        # build docker compose
        cd ${docker_work_dir}
        docker-compose stop ${fe_docker}
        docker-compose build ${fe_docker}
        ;;
    all)
        $0 env $2
        $0 base
        $0 jar
        $0 fe
        $0 upgdb
        ;;                                  
    rm)
        case "$2" in
            base)
                cd ${docker_work_dir}
                docker-compose stop ${base_dockers}
                for base_docker in ${base_dockers}; do
                    docker rm ${base_docker}
                done   
                ;;
            jar)
                cd ${docker_work_dir}
                docker-compose stop ${jar_dockers}
                docker rm ${jar_dockers}
                if [ ! -z "${wfc_jar_images}" ]; then
                    docker rmi ${wfc_jar_images} 
                fi
               
                # for jar_docker in ${jar_dockers}; do
                #     docker rm ${jar_docker}
                #     docker rmi docker_${jar_docker}                
                # done               
                ;;
            modules)
                cd ${docker_work_dir}
                docker-compose stop ${modules_dockers}
                docker rm ${modules_dockers}
                if [ ! -z "${wfc_modules_images}" ]; then
                    docker rmi ${wfc_modules_images} 
                fi
           
                # for modules_docker in ${modules_dockers}; do
                #     docker rm ${modules_docker}
                #     docker rmi docker_${modules_docker}
                #     docker rmi docker-${modules_docker}
                # done               
                ;;
            fe)
                cd ${docker_work_dir}
                docker-compose stop ${fe_docker}
                docker rm ${fe_docker}
                # docker rmi nginx                    
                ;;
            network)
                cd ${docker_work_dir}
                docker-compose stop
                docker network rm wfc-fe-network
                docker network rm wfc-be-network
                ;;
            all)
                $0 rm base
                $0 rm jar
                $0 rm fe
                $0 rm network
                ;;
            *)
                echo "WANFi Control and Billing System Setup ... "
                echo "Usage: $0 rm [base|jar|modules|fe|network|all]"
                exit 1 
                ;;               
        esac
        ;;
    prune)
        cd ${docker_work_dir}
        docker-compose down
        docker system prune -a
        ;;
    *)
        echo "WANFi Control and Billing System Setup ... "
        echo "Usage: $0 env|initdb|upgdb|base|jar|modules|fe|all|rm [base|jar|modules|fe|network|all]|prune"
        echo "       $0 env [IP]"
        echo "       $0 initdb"
        echo "       $0 upgdb"
        echo "       $0 base|jar|modules|fe"
        echo "       $0 all [IP]"
        echo "       $0 rm [base|jar|modules|fe|network|all]"
        echo "       $0 prune"
        exit 1
        ;;
esac



