#!/usr/bin/env bash
# Set up the software for a new business on this server.
#
#   bash new-client.sh <id> <release.zip>
#
# Before running: in hPanel, create the subdomain (e.g. client2.karanshah.ca) and an empty
# MySQL database with its own user. This script asks for those details, fills in the .env,
# installs, creates the owner login and adds the client to ~/LemonLogicSoftware/clients.conf.
# Every client's app folder lives in ~/LemonLogicSoftware/<Name>-WebApp (LLS_HOME=... to change).
set -euo pipefail

ID="${1:-}"; ZIP="${2:-}"
if [ -z "$ID" ] || [ -z "$ZIP" ] || [ ! -f "$ZIP" ]; then
  echo "Usage: bash new-client.sh <id> <release.zip>     (id: short name, letters/digits/-)"
  exit 1
fi
[[ "$ID" =~ ^[a-z0-9-]+$ ]] || { echo "*** id must be lowercase letters, digits or -"; exit 1; }
ZIP="$(cd "$(dirname "$ZIP")" && pwd)/$(basename "$ZIP")"
LLS_HOME="${LLS_HOME:-$HOME/LemonLogicSoftware}"
mkdir -p "$LLS_HOME"
CLIENTS_FILE="${CLIENTS_FILE:-$LLS_HOME/clients.conf}"
if [ -f "$CLIENTS_FILE" ] && awk '{print $1}' "$CLIENTS_FILE" | grep -qx "$ID"; then
  echo "*** $ID is already in $CLIENTS_FILE"; exit 1
fi
if [ -z "${PHP:-}" ]; then
  if [ -x /opt/alt/php83/usr/bin/php ]; then PHP=/opt/alt/php83/usr/bin/php; else PHP=php; fi
fi
export PHP

DOMAIN_DIR_DEFAULT="$HOME/domains/karanshah.ca"
read -rp "Business name (shown in the app): " NAME
read -rp "App address [https://$ID.karanshah.ca]: " URL;            URL="${URL:-https://$ID.karanshah.ca}"
# shreeji -> Shreeji-WebApp, another-client -> Another-Client-WebApp
FOLDER_DEFAULT="$(echo "$ID" | sed -E 's/(^|-)([a-z])/\1\u\2/g')-WebApp"
read -rp "App folder [$LLS_HOME/$FOLDER_DEFAULT]: " APP;          APP="${APP:-$LLS_HOME/$FOLDER_DEFAULT}"
read -rp "Website folder of the subdomain [$DOMAIN_DIR_DEFAULT/public_html/$ID]: " WEB; WEB="${WEB:-$DOMAIN_DIR_DEFAULT/public_html/$ID}"
# A typed "~/..." is not expanded by read; turn it into the real home path.
APP="${APP/#\~/$HOME}"; WEB="${WEB/#\~/$HOME}"
case "$APP" in /*) ;; *) echo "*** App folder must be a full path (starting with / or ~/)"; exit 1 ;; esac
case "$WEB" in /*) ;; *) echo "*** Website folder must be a full path (starting with / or ~/)"; exit 1 ;; esac
read -rp "Database name: " DB_NAME
read -rp "Database user: " DB_USER
read -rsp "Database password: " DB_PASS; echo
read -rp "Order number prefix (e.g. SC) [${ID^^}]: " PREFIX;         PREFIX="${PREFIX:-${ID^^}}"
read -rp "Colour (orange, indigo, sky, teal, cyan, fuchsia) [orange]: " COLOR; COLOR="${COLOR:-orange}"
echo "Licence lines come from the licence dashboard (New client → copy the 3 lines). Leave empty to add later."
read -rp "LICENSE_KEY: " LKEY
read -rp "LICENSE_SERVER_URL: " LURL
read -rp "LICENSE_PUBLIC_KEY: " LPUB
read -rp "Channel for releases (stable / beta) [stable]: " CHANNEL; CHANNEL="${CHANNEL:-stable}"

if [ -d "$APP" ] && [ -n "$(ls -A "$APP" 2>/dev/null)" ]; then
  echo "*** $APP is not empty. Pick another folder."; exit 1
fi
mkdir -p "$APP"
unzip -q -o "$ZIP" -d "$APP"
cd "$APP"
cp deploy/env.production.example .env

setenv() { # setenv KEY VALUE  (adds or replaces a line in .env)
  local k="$1" v="$2"
  v="${v//\\/\\\\}"; v="${v//&/\\&}"; v="${v//|/\\|}"
  if grep -q "^$k=" .env; then sed -i "s|^$k=.*|$k=$v|" .env; else echo "$k=$v" >> .env; fi
}
setenv APP_NAME "\"$NAME\""
setenv APP_URL "$URL"
setenv DB_DATABASE "$DB_NAME"
setenv DB_USERNAME "$DB_USER"
setenv DB_PASSWORD "\"$DB_PASS\""
setenv BRAND_COLOR "$COLOR"
setenv MAIL_FROM_NAME "\"$NAME\""
setenv LICENSE_KEY "$LKEY"
setenv LICENSE_SERVER_URL "$LURL"
setenv LICENSE_PUBLIC_KEY "$LPUB"

WEB="$WEB" bash deploy/deploy.sh

echo "==> Base data (roles, units, settings)"
$PHP artisan db:seed --class=RolesAndPermissionsSeeder --force
$PHP artisan db:seed --class=BaseDataSeeder --force
$PHP artisan tinker --execute="App\Models\Setting::set('order_prefix', '$PREFIX'); App\Models\Setting::set('company_name', config('app.name'));" >/dev/null

echo "==> Owner login for $NAME"
$PHP artisan app:create-owner

printf '%-12s %-44s %-46s %s\n' "$ID" "$APP" "$WEB" "$CHANNEL" >> "$CLIENTS_FILE"
echo
echo "==> $NAME is ready at $URL"
echo "    Added to $CLIENTS_FILE, so release.sh --all now includes it."
echo "    Last step, in hPanel › Cron jobs, every minute:"
echo "    $PHP $APP/artisan schedule:run >> /dev/null 2>&1"
[ -n "$LKEY" ] && $PHP artisan license:check || true
