#!/usr/bin/env bash # Install (or upgrade) __TITLE__ on a Linux server. Paste one line into a fresh server: # # Public repo: # curl -fsSL __INSTALL_URL__ | bash # # Private repo over https (the token is asked for, not typed into history): # read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash # # Private repo over SSH: copy this file to the server, then # GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh # # What it does: installs git and Docker (Engine + Compose) if missing, clones the repo into # $INSTALL_DIR, writes $INSTALL_DIR/.env (repo URL, branch, credentials, port) for the # container's `update`, builds the image, starts the container and waits until it is # healthy. Re-running it is safe: it keeps .env (values you pass replace those keys), # pulls the checkout, rebuilds the image and restarts. Run it again whenever container/ # changes; for ordinary deploys use `docker exec __NAME__ update`. # # Settings (environment variables, all optional): # INSTALL_DIR default /opt/__NAME__ # REPO_URL default __REPO_URL__ # REPO_REF default __BRANCH__ # GIT_TOKEN, GIT_USERNAME private repo over https # GIT_SSH_KEY private repo over SSH (base64-encoded deploy key) # HOST_PORT default __PORT__ (bound to 127.0.0.1) # # Everything is inside main(), so a partial download runs nothing. main() { set -euo pipefail local NAME=__NAME__ INSTALL_DIR=${INSTALL_DIR:-/opt/$NAME} local DEFAULT_REPO_URL="__REPO_URL__" DEFAULT_REF="__BRANCH__" DEFAULT_PORT="__PORT__" # Which keys the caller passed explicitly (these replace values in an existing .env). local passed=() for k in REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT; do [ -n "${!k:-}" ] && passed+=("$k") done [ "$(uname -s)" = Linux ] || die "this installer is for Linux servers" SUDO= if [ "$(id -u)" != 0 ]; then command -v sudo >/dev/null || die "run as root, or install sudo" SUDO=sudo fi step "prerequisites" install_packages install_docker step "source" load_existing_env REPO_URL=${REPO_URL:-$DEFAULT_REPO_URL} REPO_REF=${REPO_REF:-$DEFAULT_REF} HOST_PORT=${HOST_PORT:-$DEFAULT_PORT} git_auth check_access checkout step "configuration" write_env step "container" (cd "$INSTALL_DIR" && $DOCKER compose up -d --build --remove-orphans) wait_healthy step "done" cat </dev/null || { [ -n "$SUDO" ] && $SUDO "$@"; }; } read_file() { if [ -r "$1" ]; then cat "$1"; else $SUDO cat "$1"; fi; } step() { printf '\n==> %s\n' "$*"; } log() { printf ' %s\n' "$*"; } die() { printf '\nerror: %s\n' "$*" >&2; exit 1; } install_packages() { local need=() command -v git >/dev/null || need+=(git) command -v curl >/dev/null || need+=(curl) command -v ssh >/dev/null || need+=(ssh) [ ${#need[@]} -eq 0 ] && { log "git, curl, ssh: present"; return; } log "installing ${need[*]}" if command -v apt-get >/dev/null; then local pkgs=("${need[@]/ssh/openssh-client}") $SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ca-certificates "${pkgs[@]}" >/dev/null elif command -v dnf >/dev/null; then $SUDO dnf install -y -q ca-certificates "${need[@]/ssh/openssh-clients}" elif command -v apk >/dev/null; then $SUDO apk add -q ca-certificates "${need[@]/ssh/openssh-client}" else die "no apt-get, dnf or apk: install ${need[*]} yourself and re-run" fi } install_docker() { if ! command -v docker >/dev/null; then log "installing Docker Engine + Compose (get.docker.com)" local dlog; dlog=$(mktemp) curl -fsSL https://get.docker.com | $SUDO sh >"$dlog" 2>&1 || { tail -20 "$dlog" >&2; die "Docker install failed (full log: $dlog)"; } rm -f "$dlog" fi if ! docker info >/dev/null 2>&1 && ! $SUDO docker info >/dev/null 2>&1 \ && command -v systemctl >/dev/null && [ -d /run/systemd/system ]; then $SUDO systemctl enable --now docker >/dev/null 2>&1 || true fi if docker info >/dev/null 2>&1; then DOCKER=docker; else DOCKER="$SUDO docker"; fi $DOCKER info >/dev/null 2>&1 || die "Docker is installed but the daemon is not running" $DOCKER compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (apt-get install docker-compose-plugin)" log "docker $($DOCKER version --format '{{.Server.Version}}'), compose $($DOCKER compose version --short)" } # Values already in .env fill in whatever the caller did not pass. load_existing_env() { local f="$INSTALL_DIR/.env" line key val [ -f "$f" ] || return 0 log "keeping existing $f" while IFS= read -r line || [ -n "$line" ]; do line=${line%$'\r'} [[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]} if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi case $key in REPO_URL|REPO_REF|GIT_TOKEN|GIT_USERNAME|GIT_SSH_KEY|HOST_PORT) [ -n "${!key:-}" ] || printf -v "$key" '%s' "$val" ;; esac done < <(read_file "$f") } # Credentials reach git through the environment only; nothing is stored in the checkout. git_auth() { export GIT_TERMINAL_PROMPT=0 if [ -n "${GIT_TOKEN:-}" ]; then export GIT_TOKEN GIT_USERNAME="${GIT_USERNAME:-}" export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f' fi local ssh="ssh -o StrictHostKeyChecking=accept-new" if [ -n "${GIT_SSH_KEY:-}" ]; then KEYFILE=$(mktemp); trap 'rm -f "$KEYFILE"' EXIT printf '%s' "$GIT_SSH_KEY" | base64 -d > "$KEYFILE" 2>/dev/null || die "GIT_SSH_KEY is not valid base64 (use: base64 -w0 deploy_key)" ssh="$ssh -i $KEYFILE -o IdentitiesOnly=yes" fi export GIT_SSH_COMMAND="$ssh" } check_access() { git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable: $(redact "$REPO_URL") ($REPO_REF)"; return; } # Private https repo and no token yet: ask on the terminal (stdin is this script). if [ -z "${GIT_TOKEN:-}" ] && [[ $REPO_URL == https://* ]] && [ -r /dev/tty ]; then printf ' %s needs a token. Git token (read-only): ' "$(redact "$REPO_URL")" > /dev/tty IFS= read -rs GIT_TOKEN < /dev/tty; echo > /dev/tty passed+=(GIT_TOKEN) git_auth git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable with token"; return; } fi die "cannot read $REPO_REF from $(redact "$REPO_URL"). Check REPO_URL/REPO_REF, and pass GIT_TOKEN (https) or GIT_SSH_KEY (ssh) for a private repo" } # The host checkout holds compose.yml and container/ (what the image is built from). # The app itself runs from the container's own checkout, which `update` manages. checkout() { if [ ! -d "$INSTALL_DIR/.git" ]; then priv mkdir -p "$INSTALL_DIR" [ -w "$INSTALL_DIR" ] || $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR" [ -z "$(ls -A "$INSTALL_DIR" | grep -vx .env || true)" ] || die "$INSTALL_DIR exists and is not a checkout of $NAME" log "new checkout in $INSTALL_DIR" git -C "$INSTALL_DIR" init --quiet git -C "$INSTALL_DIR" remote add origin "$REPO_URL" fi # First install and re-runs alike: fetch and check out REPO_REF. git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL" git -C "$INSTALL_DIR" fetch --quiet --prune --tags origin local target target=$(git -C "$INSTALL_DIR" rev-parse --verify --quiet "origin/$REPO_REF^{commit}" || git -C "$INSTALL_DIR" rev-parse --verify "$REPO_REF^{commit}") git -C "$INSTALL_DIR" reset --quiet --hard "$target" log "at $(git -C "$INSTALL_DIR" log -1 --format='%h %s')" } # .env: created from .env.example on first install; on re-runs only the keys the caller # passed are replaced. Owned by uid 1000 (the container's user), group = installer, mode 640. write_env() { local f="$INSTALL_DIR/.env" tmp line key out=() seen=" " if [ -f "$f" ]; then mapfile -t lines < <(read_file "$f"); else mapfile -t lines < "$INSTALL_DIR/.env.example" passed=(REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT) log "writing $f" fi for line in "${lines[@]}"; do key=${line%%=*} if [[ $line =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && [[ " ${passed[*]} " == *" $key "* ]]; then out+=("$key=${!key:-}"); seen+="$key " else out+=("$line"); fi done for key in "${passed[@]}"; do [[ $seen == *" $key "* ]] || out+=("$key=${!key:-}"); done tmp=$(mktemp) printf '%s\n' "${out[@]}" > "$tmp" priv install -m 640 -o 1000 -g "$(id -g)" "$tmp" "$f" || die "could not write $f" rm -f "$tmp" [ ${#passed[@]} -eq 0 ] || log "set in .env: ${passed[*]}" } health_version() { $DOCKER exec "$NAME" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen(f"http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null } wait_healthy() { log "waiting for the app (first start clones the repo and installs requirements)" for _ in $(seq 1 180); do [ -n "$(health_version)" ] && { log "healthy at $(health_version)"; return; } [ "$($DOCKER inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = false ] && break sleep 1 done $DOCKER logs --tail 40 "$NAME" >&2 || true die "$NAME did not become healthy (logs above)" } redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; } main "$@"