#!/bin/bash
set -euo pipefail

# fx is a CLI, not a daemon: it has nothing to serve. The long-running
# process of this package is therefore the auth-proxied landing page on
# the Cloudron HTTP port (health check + usage guide). The fx binary and
# the persistent workspace below are driven interactively from the
# Cloudron web terminal (App -> terminal, or `cloudron exec`).
#
# Workspace layout seeded on first run:
#   /app/data/functions/  function sources (two starter functions)
#   /app/data/ssh/        SSH keys for remote Docker targets
#   /app/data/kube/       kubeconfig for Kubernetes targets

mkdir -p /app/data/functions /app/data/ssh /app/data/kube

# Starter functions, exactly the upstream example shapes (Koa-style ctx
# for JavaScript, plain callable for Python).
if [[ ! -f /app/data/functions/hello.js ]]; then
  cat > /app/data/functions/hello.js <<'EOF'
module.exports = (ctx) => {
  ctx.body = 'hello world'
}
EOF
fi

if [[ ! -f /app/data/functions/hello.py ]]; then
  cat > /app/data/functions/hello.py <<'EOF'
def fx(request):
    return "hello world"
EOF
fi

echo "fx $(/usr/local/bin/fx -v) ready - open the app's web terminal to use it."
echo "Workspace: /app/data/functions (sources), /app/data/ssh (keys), /app/data/kube (kubeconfig)"
echo "Deploy example: fx up --host <user>@<host> --ssh_key /app/data/ssh/id_rsa --name hello /app/data/functions/hello.js"

# Landing page (health check + auth-proxied usage guide) is the only
# long-running process - fx itself runs on demand from the terminal.
exec python3 -m http.server "${CLOUDRON_HTTP_PORT:-8000}" --directory /app/code/status
