#!/usr/bin/env bash
# Installer central : un dossier privé + un point d'accès PHP temporaire.
set -euo pipefail
umask 077
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HOME="${HOME:?}"
STORE="$HOME/.cpanel-mega-ui"

for dep in python3 php uapi rclone; do
  command -v "$dep" >/dev/null || { echo "DEPENDANCE_MANQUANTE: $dep"; exit 1; }
done
python3 - <<'PY'
import sys
assert sys.version_info >= (3,9), 'Python >= 3.9 requis'
PY
php -l "$ROOT/public/index.php" | grep -q 'No syntax errors'
python3 -m py_compile "$ROOT/private/engine.py"

if [[ -e "$STORE/auth.json" ]]; then
 echo "DEJA_INSTALLE: $STORE"; exit 1
fi

# Découverte du document root du domaine principal par cPanel.
export CP_USER="$(id -un)"
ROOT_INFO="$(python3 - <<'PY'
import json,os,subprocess,sys
user=os.environ['CP_USER']
p=subprocess.run(['uapi',f'--user={user}','--output=json','DomainInfo','domains_data','format=hash'],capture_output=True,text=True)
if p.returncode:sys.exit('ERREUR_UAPI_DOCUMENT_ROOT')
d=json.loads(p.stdout).get('result',{}).get('data',{})
r=d.get('main_domain',{})
if isinstance(r,list):r=r[0] if r else {}
path=(r.get('documentroot') or r.get('document_root') or r.get('docroot') or '') if isinstance(r,dict) else ''
if not path:sys.exit('DOCUMENT_ROOT_PRINCIPAL_NON_DETECTE')
print((r.get("domain") or r.get("servername") or "").strip()+"|"+path)
PY
)"
ROOT_DOMAIN="${ROOT_INFO%%|*}"
ROOT_DOC="${ROOT_INFO#*|}"
if [[ -z "$ROOT_DOC" || ! -d "$ROOT_DOC" || "$ROOT_DOC" != "$HOME"/* ]]; then
 echo "DOCUMENT_ROOT_INVALIDE: $ROOT_DOC"; exit 1
fi

printf 'Mot de passe pour l’interface (minimum 14 caractères) : '
IFS= read -r -s PASS; printf '\n'
printf 'Confirmer le mot de passe : '
IFS= read -r -s PASS2; printf '\n'
if [[ "$PASS" != "$PASS2" || ${#PASS} -lt 14 ]]; then echo "MOT_DE_PASSE_NON_CONFORME"; exit 1; fi
unset PASS2
HASH="$(printf '%s' "$PASS" | php -r 'echo password_hash(stream_get_contents(STDIN), PASSWORD_DEFAULT);')"
unset PASS

PUBLIC_ID="_ops_$(python3 - <<'PY'
import secrets;print(secrets.token_hex(9))
PY
)"
TARGET="$ROOT_DOC/$PUBLIC_ID"
mkdir -p "$STORE" "$STORE/plans" "$STORE/jobs" "$STORE/work" "$TARGET"
chmod 700 "$STORE" "$STORE/plans" "$STORE/jobs" "$STORE/work"
cp "$ROOT/private/engine.py" "$STORE/engine.py"
cp "$ROOT/uninstall.sh" "$STORE/uninstall.sh"
chmod 600 "$STORE/engine.py"
chmod 700 "$STORE/uninstall.sh"
export HASH STORE TARGET
python3 - <<'PY'
import json,os,pathlib
store=pathlib.Path(os.environ['STORE'])
(store/'auth.json').write_text(json.dumps({'password_hash':os.environ['HASH']}))
(store/'auth.json').chmod(0o600)
PY
PYTHON_BIN="$(command -v python3)"
python3 - "$ROOT/public/index.php" "$TARGET/index.php" "$STORE" "$PYTHON_BIN" <<'PY'
from pathlib import Path
import sys
text=Path(sys.argv[1]).read_text()
Path(sys.argv[2]).write_text(text.replace('__PRIVATE_HOME__',sys.argv[3]).replace('__PYTHON_BIN__',sys.argv[4]))
PY
cat > "$TARGET/.htaccess" <<'HT'
Options -Indexes
DirectoryIndex index.php
<FilesMatch "^(?!index\.php$).+">
  Require all denied
</FilesMatch>
HT
chmod 750 "$TARGET"; chmod 640 "$TARGET/index.php" "$TARGET/.htaccess"
printf '%s\n' "$TARGET" > "$STORE/public_path"
chmod 600 "$STORE/public_path"

echo "INSTALLATION_OK"
echo "Chemin de l'interface : $TARGET"
echo "URL : https://$ROOT_DOMAIN/$PUBLIC_ID/index.php"
echo "IMPORTANT: renseigner le nom de domaine principal dans l'URL; aucune suppression n'a été exécutée."
