#!/usr/bin/env bash
set -euo pipefail

APP_DIR="/var/www/muxiyeto-com/phenocrypto"
RELEASE_DIR="/tmp/phenocrypto-release"
SERVICE_FILE="/etc/systemd/system/phenocrypto.service"
ENV_FILE="/etc/phenocrypto.env"
SSL_CONF="/etc/apache2/sites-enabled/muxiyeto-com-le-ssl.conf"
PORT="3105"
STAMP="$(date +%Y%m%d-%H%M%S)"

if [[ ! -d "$RELEASE_DIR/kraken_bot" ]]; then
  echo "Missing release at $RELEASE_DIR" >&2
  exit 1
fi

if [[ -d "$APP_DIR" ]]; then
  tar -czf "${APP_DIR}.bak-${STAMP}.tgz" -C "$(dirname "$APP_DIR")" "$(basename "$APP_DIR")"
  if [[ -d "$APP_DIR/state" ]]; then
    rm -rf /tmp/phenocrypto-state-preserve
    cp -a "$APP_DIR/state" /tmp/phenocrypto-state-preserve
  fi
fi

rm -rf "$APP_DIR"
mkdir -p "$APP_DIR"
cp -a "$RELEASE_DIR"/. "$APP_DIR"/
if [[ -d /tmp/phenocrypto-state-preserve ]]; then
  rm -rf "$APP_DIR/state"
  cp -a /tmp/phenocrypto-state-preserve "$APP_DIR/state"
  rm -rf /tmp/phenocrypto-state-preserve
fi
chown -R www-data:www-data "$APP_DIR"

ADMIN_TOKEN=""
LOGIN_USERNAME="admin"
LOGIN_PASSWORD=""
SESSION_SECRET=""
if [[ -f "$ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$ENV_FILE" || true
  ADMIN_TOKEN="${PHENOCRYPTO_ADMIN_TOKEN:-}"
  LOGIN_USERNAME="${PHENOCRYPTO_USERNAME:-admin}"
  LOGIN_PASSWORD="${PHENOCRYPTO_PASSWORD:-}"
  SESSION_SECRET="${PHENOCRYPTO_SESSION_SECRET:-}"
fi
if [[ -z "$ADMIN_TOKEN" ]]; then
  ADMIN_TOKEN="$(openssl rand -hex 24)"
fi
if [[ -z "$LOGIN_PASSWORD" ]]; then
  LOGIN_PASSWORD="$(openssl rand -base64 18 | tr -d '=+/')"
fi
if [[ -z "$SESSION_SECRET" ]]; then
  SESSION_SECRET="$(openssl rand -hex 32)"
fi

cat > "$ENV_FILE" <<EOF
PHENOCRYPTO_HOST=127.0.0.1
PHENOCRYPTO_PORT=$PORT
PHENOCRYPTO_BASE_PATH=/phenocrypto
PHENOCRYPTO_ADMIN_TOKEN=$ADMIN_TOKEN
PHENOCRYPTO_USERNAME=$LOGIN_USERNAME
PHENOCRYPTO_PASSWORD=$LOGIN_PASSWORD
PHENOCRYPTO_SESSION_SECRET=$SESSION_SECRET
PHENOCRYPTO_LOG_LEVEL=INFO
EOF
chmod 600 "$ENV_FILE"
chown root:root "$ENV_FILE"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Phenocrypto Kraken Trading Bot Web Dashboard
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=$APP_DIR
EnvironmentFile=$ENV_FILE
ExecStart=/usr/bin/python3 -m kraken_bot.web.app --config config.example.json --host 127.0.0.1 --port $PORT --base-path /phenocrypto
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

rm -f /etc/sudoers.d/phenocrypto-service

python3 -m compileall -q "$APP_DIR/kraken_bot" "$APP_DIR/tests"
(cd "$APP_DIR" && /usr/bin/python3 -m unittest discover -s tests -v)

systemctl daemon-reload
systemctl enable phenocrypto.service >/dev/null
systemctl restart phenocrypto.service
sleep 2
systemctl is-active --quiet phenocrypto.service

if ! grep -q "ProxyPass[[:space:]]*/phenocrypto/" "$SSL_CONF"; then
  cp "$SSL_CONF" "${SSL_CONF}.bak-phenocrypto-${STAMP}"
  python3 - "$SSL_CONF" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
text = path.read_text()
block = """
ProxyPass        /phenocrypto/ http://127.0.0.1:3105/phenocrypto/
ProxyPassReverse /phenocrypto/ http://127.0.0.1:3105/phenocrypto/

RedirectMatch 301 ^/phenocrypto$ /phenocrypto/

"""
marker = "</VirtualHost>"
if marker not in text:
    raise SystemExit("Could not find </VirtualHost> marker")
path.write_text(text.replace(marker, block + marker, 1))
PY
fi

apache2ctl configtest
systemctl reload apache2

curl -fsS "http://127.0.0.1:$PORT/phenocrypto/login" >/tmp/phenocrypto-login.html
curl -kfsS "https://muxiyeto.com/phenocrypto/login" >/tmp/phenocrypto-public-login.html

echo "installed=$APP_DIR"
echo "service=phenocrypto.service"
echo "url=https://muxiyeto.com/phenocrypto/"
echo "username=$LOGIN_USERNAME"
echo "password=$LOGIN_PASSWORD"
echo "admin_token=$ADMIN_TOKEN"
