#!/bin/sh
set -eu

export LC_ALL=C

file_1=/workspace/wwwroot/datacenter/project/application/cron/shell/prod/sync_breezingpro.sh
file_2=/workspace/wwwroot/tnxlahtks/project/application/cron/shell/prod/sync_eliga_data_v1.sh
file_3=/workspace/wwwroot/tnxlahtks/project/application/cron/shell/prod/sync_eliga_data.sh
file_4=/workspace/wwwroot/tjkx/project/application/cron/shell/prod/sync_tj_medical.sh
file_5=/workspace/wwwroot/sxkx/project/application/cron/shell/prod/deal_wattbike_data.sh

validate_file() {
    file_path=$1
    sh -n "$file_path"
    guard_count=$(grep -F -c 'if [ "$(id -u)" -eq 0 ]; then' "$file_path")
    unguarded_count=$(grep -E -c '^chown -R www:www /workspace/wwwroot/log/?$' "$file_path" || true)
    owner=$(stat -c %U:%G "$file_path")
    mode=$(stat -c %a "$file_path")
    [ "$guard_count" -eq 1 ]
    [ "$unguarded_count" -eq 0 ]
    [ "$owner" = www:www ]
    [ "$mode" = 755 ]
    printf "file_ok guard=%s unguarded=%s owner=%s mode=%s file=%s\n" \
        "$guard_count" "$unguarded_count" "$owner" "$mode" "$file_path"
}

validate_file "$file_1"
validate_file "$file_2"
validate_file "$file_3"
validate_file "$file_4"
validate_file "$file_5"

sha256sum -c /workspace/zhct-backups/ECS-CRON-CHOWN-FIX-20260819-01/archive.sha256

for process_name in mysqld nginx php-fpm; do
    if pgrep -x "$process_name" >/dev/null 2>&1; then
        printf "%s=active\n" "$process_name"
    else
        printf "%s=missing\n" "$process_name"
        exit 51
    fi
done

for port in 80 443 3306; do
    if ss -lnt | awk '{print $4}' | grep -Eq ":${port}$"; then
        printf "port_%s=listening\n" "$port"
    else
        printf "port_%s=missing\n" "$port"
        exit 52
    fi
done

http_code=$(curl -k -sS -o /dev/null -w "%{http_code}" --max-time 10 http://127.0.0.1/)
printf "http_code=%s\n" "$http_code"
[ "$http_code" = 301 ]

root_usage=$(df -P / | awk 'NR == 2 {gsub(/%/, "", $5); print $5}')
printf "root_usage_percent=%s\n" "$root_usage"
[ "$root_usage" -lt 90 ]

df -hP / /workspace
echo VALIDATION_SUCCESS
