#!/bin/bash
################################################################################
# Script Name: version/3.0.7/UPDATE.sh
# Description: Apply version 3.0.7 migrations: add plans.subdomains_limit so
#              a hosting plan can cap subdomains, on top of domains_limit
#              which now counts them too.
# Company: hitechcloud.org
# Copyright (c) hitechcloud.org
################################################################################

set -uo pipefail
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
ok()   { echo -e "[3.0.7] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.0.7] ${YELLOW}!${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.0.7] This update must run as root." >&2; exit 1; }

# Before 3.0.7, a subdomain of a domain the same account already owned did
# not count toward domains_limit at all (the CLI's own check excluded it),
# so a free account could create unlimited subdomains. domains_limit now
# counts every row in `domains`, apex and subdomain alike, and this column
# adds a second, narrower cap on subdomains specifically. 0 = unlimited,
# same as every other limit on this table, so a server that does not set it
# keeps behaving exactly as it did before this column existed.
#
# ADD COLUMN is guarded by information_schema rather than by IF NOT EXISTS:
# MariaDB supports that spelling and MySQL does not, and a panel that has
# been migrated between the two would fail here on the version that does
# not (see version/2.1.24/UPDATE.sh, which added two other plans columns
# the same way).
if ! mysql -N -B -e "SELECT 1 FROM panel.plans LIMIT 1;" >/dev/null 2>&1; then
    warn "The panel database could not be read, so plans.subdomains_limit was not added."
    ok "3.0.7 update steps completed (no panel database)"
    exit 0
fi

present=$(mysql -N -B -e "SELECT COUNT(*) FROM information_schema.columns
    WHERE table_schema='panel' AND table_name='plans' AND column_name='subdomains_limit';" 2>/dev/null)

if [[ "$present" == "0" ]]; then
    if mysql panel -e "ALTER TABLE plans ADD COLUMN subdomains_limit INT NOT NULL DEFAULT 0;" 2>/dev/null; then
        ok "plans.subdomains_limit added (0 = unlimited on every existing plan)"
    else
        warn "plans.subdomains_limit could not be added - the subdomains limit will not be enforced until it is"
    fi
else
    ok "plans.subdomains_limit already present"
fi

ok "3.0.7 update steps completed successfully"
exit 0
