#!/usr/bin/env bash
# ============================================================================
#  The Meat Brand: installer
#
#  1. Put this folder somewhere outside your website folders, e.g. /opt/meat-brand
#  2. Run:   sudo bash install.sh
#  3. Answer the questions. That's it.
#
#  Works on:
#   - a cPanel/WHM VPS (keeps your existing sites and email; uses Apache + AutoSSL)
#   - a plain Ubuntu/Debian/AlmaLinux VPS (uses the built-in Caddy web server)
#
#  Safe to run again. On an existing install it updates and restarts.
# ============================================================================
set -euo pipefail
cd "$(dirname "$(readlink -f "$0")")"
APP_DIR="$(pwd)"

bold=$'\e[1m'; green=$'\e[32m'; yellow=$'\e[33m'; red=$'\e[31m'; reset=$'\e[0m'
say()  { printf '\n%s==> %s%s\n' "$bold" "$*" "$reset"; }
ok()   { printf '%s    ✓ %s%s\n' "$green" "$*" "$reset"; }
warn() { printf '%s    ! %s%s\n' "$yellow" "$*" "$reset"; }
die()  { printf '\n%sERROR: %s%s\n\n' "$red" "$*" "$reset"; exit 1; }
ask() { # ask VAR "Question" "default"
  local __v; read -r -p "    $2${3:+ [$3]}: " __v; __v="${__v:-${3:-}}"
  [ -n "$__v" ] || die "An answer is required."; printf -v "$1" '%s' "$__v"
}
ask_secret() {
  local a b
  while true; do
    read -r -s -p "    $2: " a; echo
    [ ${#a} -ge 12 ] || { warn "Use at least 12 characters."; continue; }
    read -r -s -p "    Type it again: " b; echo
    [ "$a" = "$b" ] && break; warn "They didn't match. Try again."
  done
  printf -v "$1" '%s' "$a"
}
set_env() { # set_env KEY VALUE (in .env)
  if grep -q "^$1=" .env; then sed -i "s|^$1=.*|$1=$2|" .env; else printf '%s=%s\n' "$1" "$2" >> .env; fi
}
get_env() { grep -E "^$1=" .env 2>/dev/null | head -1 | cut -d= -f2- || true; }

# ---------------------------------------------------------------------------
[ "$(id -u)" = 0 ] || die "Please run as root:  sudo bash install.sh"
case "$APP_DIR" in
  */public_html*|*/www/*|*/htdocs*)
    die "This folder is inside a public website folder, so anyone could download it.
       Move it first, then run the installer from there:
         mv \"$APP_DIR\" /opt/meat-brand && cd /opt/meat-brand && sudo bash install.sh" ;;
esac

MODE=standard
[ -x /usr/local/cpanel/cpanel ] || [ -d /usr/local/cpanel ] && MODE=cpanel

printf '\n%sThe Meat Brand installer%s  (%s server detected)\n' "$bold" "$reset" "$([ $MODE = cpanel ] && echo cPanel || echo plain)"

# ---------------------------------------------------------------------------
# Already installed? Then this is an update.
if [ -f .env ] && [ -f .installed ]; then
  say "Existing install found. Updating."
  bash scripts/deploy.sh
  [ "$MODE" = cpanel ] && bash scripts/cpanel-sync.sh
  ok "Updated. $(get_env PLATFORM_DOMAIN) is running the new version."
  exit 0
fi

# ---------------------------------------------------------------------------
say "A few questions"
CUR_DOMAIN="$(get_env PLATFORM_DOMAIN)"; [ "$CUR_DOMAIN" = "themeatbrand.com" ] && CUR_DOMAIN=""
ask DOMAIN "Your platform's domain (e.g. meatbrand.com.au)" "$CUR_DOMAIN"
DOMAIN="$(printf '%s' "$DOMAIN" | tr 'A-Z' 'a-z' | sed -E 's#^https?://##; s#/.*$##; s#^www\.##')"
[[ "$DOMAIN" =~ ^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$ ]] || die "\"$DOMAIN\" doesn't look like a domain."
ask EMAIL "Your email (for SSL certificates)" "$(get_env ACME_EMAIL | grep -v '^you@example.com$' || true)"
if [ ! -f .admin-created ]; then
  ask ADMIN_EMAIL "Email for your admin login" "$EMAIL"
  ask_secret ADMIN_PASSWORD "Choose your admin password (12+ characters)"
fi

if [ "$MODE" = cpanel ]; then
  CPUSER="$(/scripts/whoowns "$DOMAIN" 2>/dev/null || true)"
  [ -n "$CPUSER" ] || die "$DOMAIN isn't a cPanel account on this server yet.
       In WHM go to 'Create a New Account', create one for $DOMAIN, then run this again."
  echo
  warn "https://$DOMAIN (and www.) will show the platform instead of whatever is in"
  warn "the '$CPUSER' account's website folder. Email and other accounts are not affected."
  warn "You can undo this any time with: bash scripts/cpanel-sync.sh --remove"
  read -r -p "    Continue? [y/N]: " yn; [[ "$yn" =~ ^[Yy] ]] || die "Stopped. Nothing was changed."
fi

# ---------------------------------------------------------------------------
say "Settings"
if [ ! -f .env ]; then
  cp .env.example .env
  rnd() { openssl rand -hex 24; }
  set_env POSTGRES_PASSWORD "$(rnd)"
  set_env APP_DB_PASSWORD "$(rnd)"
  set_env ADMIN_DB_PASSWORD "$(rnd)"
  set_env APP_ENCRYPTION_KEY "$(openssl rand -base64 32)"
  set_env BACKUP_PASSPHRASE "$(rnd)"
  ok "Created .env with new random passwords"
fi
set_env PLATFORM_DOMAIN "$DOMAIN"
set_env EDGE_TARGET "sites.$DOMAIN"
set_env ACME_EMAIL "$EMAIL"
if [ "$MODE" = cpanel ]; then
  set_env COMPOSE_FILE "docker-compose.yml:docker-compose.cpanel.yml"
  echo "$CPUSER" > .cpanel-user
fi
chmod 600 .env
ok "Saved"

# ---------------------------------------------------------------------------
say "Docker"
if command -v docker >/dev/null && docker compose version >/dev/null 2>&1; then
  ok "Already installed ($(docker --version | cut -d, -f1))"
else
  . /etc/os-release
  if command -v apt-get >/dev/null; then
    curl -fsSL https://get.docker.com | sh >/dev/null
  elif command -v dnf >/dev/null || command -v yum >/dev/null; then
    PM=$(command -v dnf || command -v yum)
    $PM -y install dnf-plugins-core yum-utils >/dev/null 2>&1 || true
    $PM config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo >/dev/null 2>&1 \
      || yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo >/dev/null
    $PM -y install --allowerasing docker-ce docker-ce-cli containerd.io docker-compose-plugin >/dev/null
  else
    die "Unsupported system ($PRETTY_NAME). Install Docker manually, then re-run."
  fi
  systemctl enable --now docker >/dev/null
  ok "Installed"
fi

# ---------------------------------------------------------------------------
if [ "$MODE" = cpanel ]; then
  say "Preparing cPanel"
  if [ -f /etc/csf/csf.conf ]; then
    sed -i 's/^DOCKER = .*/DOCKER = "1"/' /etc/csf/csf.conf
    csf -ra >/dev/null 2>&1 || true
    ok "CSF firewall set to work with Docker"
  fi
  for m in proxy_http headers; do
    if ! httpd -M 2>/dev/null | grep -q "${m}_module"; then
      (dnf -y install "ea-apache24-mod_${m}" || yum -y install "ea-apache24-mod_${m}") >/dev/null 2>&1 \
        || die "Couldn't install Apache module mod_${m}. In WHM > EasyApache 4, enable mod_${m}, then re-run."
    fi
  done
  ok "Apache proxy modules ready"
  for p in 3100 4100; do
    if ss -ltn | grep -q "127.0.0.1:$p \|:$p "; then
      docker ps --format '{{.Ports}}' | grep -q ":$p->" || die "Port $p is already used by another program."
    fi
  done
else
  say "Firewall and ports"
  for p in 80 443; do
    if ss -ltnp | grep -E ":$p\s" | grep -vq docker; then
      die "Something else is already using port $p (another web server?):
$(ss -ltnp | grep -E ":$p\s")
       Stop it, or ask for help, then re-run."
    fi
  done
  if command -v ufw >/dev/null; then
    ufw allow OpenSSH >/dev/null; ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null; ufw allow 443/udp >/dev/null
    ufw --force enable >/dev/null; ok "Firewall: SSH, HTTP, HTTPS allowed"
  fi
fi

# ---------------------------------------------------------------------------
say "Building the platform (first time takes 5–15 minutes)"
docker compose build 2>&1 | tail -n 5
ok "Built"

say "Starting the database and applying updates"
docker compose up -d postgres redis
docker compose --profile tools run --rm migrate
ok "Database ready"

say "Starting the platform"
docker compose up -d --remove-orphans
for i in $(seq 1 60); do
  if docker compose exec -T api node -e "fetch('http://localhost:4000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" 2>/dev/null; then
    ok "Running"; break
  fi
  [ "$i" = 60 ] && die "The platform didn't start. Show this to your developer:  docker compose logs api --tail 60"
  sleep 2
done

if [ ! -f .admin-created ]; then
  say "Creating your admin login"
  ADMIN_PASSWORD="$ADMIN_PASSWORD" docker compose --profile tools run --rm -T -e ADMIN_PASSWORD \
    migrate node /repo/apps/api/dist/cli/create-admin.js "$ADMIN_EMAIL"
  touch .admin-created
  unset ADMIN_PASSWORD
fi

# ---------------------------------------------------------------------------
say "Scheduling backups$([ $MODE = cpanel ] && echo ' and site sync')"
{
  echo "# The Meat Brand (installed by install.sh)"
  echo "15 3 * * * root cd $APP_DIR && bash scripts/backup.sh >> /var/log/meatbrand-backup.log 2>&1"
  [ "$MODE" = cpanel ] && echo "*/2 * * * * root cd $APP_DIR && bash scripts/cpanel-sync.sh >> /var/log/meatbrand-cpanel-sync.log 2>&1"
} > /etc/cron.d/meatbrand
chmod 644 /etc/cron.d/meatbrand
ok "Nightly backup at 3:15am"

if [ "$MODE" = cpanel ]; then
  say "Connecting to cPanel"
  bash scripts/cpanel-sync.sh
  ok "app.$DOMAIN and sites.$DOMAIN set up; SSL certificates requested (allow ~5 minutes)"
fi

touch .installed
IP="$(curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')"

cat <<EOF

${green}${bold}Installed!${reset}

  Admin:      https://app.$DOMAIN/admin      (sign in, then set up two-factor with an authenticator app)
  Website:    https://$DOMAIN

${bold}DNS:${reset} these must point to this server ($IP):
    $DOMAIN, www.$DOMAIN, app.$DOMAIN, sites.$DOMAIN$([ $MODE = cpanel ] && echo "
    (If $DOMAIN's DNS is managed in this cPanel/WHM, this is already done for you.)" || echo ", and *.$DOMAIN")

${bold}Add a client:${reset} Admin > "Add a client site". Their preview site and SSL are set up automatically.

${bold}Do this now:${reset} save these two lines from $APP_DIR/.env in your password manager.
  Without them, backups can't be restored:
    $(grep '^APP_ENCRYPTION_KEY=' .env)
    $(grep '^BACKUP_PASSPHRASE=' .env)
  Then add off-server backup storage (BACKUP_S3_*) in .env. See docs/OPERATIONS.md.

${bold}Update later:${reset} replace this folder's files with a new version (keep .env), then run:  sudo bash install.sh
EOF
