#!/usr/bin/env bash
# Burrow Server: your family's own Burrow server, in one step (Linux with Docker).
#
#   Install:   curl -fsSL https://burrowmap.com/server/install.sh | bash
#
#   Afterwards, in the server's folder (~/burrow-server, or /opt/burrow-server when installed as root):
#     ./burrow-server status            is it running, and the address to type into the app
#     ./burrow-server reports on|off    send bug reports and app stats to the Burrow team, or not
#     ./burrow-server backup            copy the family's data now (a copy is also made every night; 7 are kept)
#     ./burrow-server update            get the newest Burrow Server (keeps the family's data and settings)
#     ./burrow-server stop | start
#     ./burrow-server uninstall [--delete-data]
#
# What it runs: Burrow's server (box.py, the same one Burrow Cloud uses; it only ever holds end-to-end encrypted
# locations, so not even this computer's owner can read them) in the official python:3.12-slim image, read-only, as its
# own user and with no internet; Caddy in front of it (https on your own web address); and a nightly backup.
#
# Answers can be given ahead (for unattended installs): BURROW_ADDRESS (a domain, or "home"), BURROW_ORGANIZER_NAME,
# BURROW_ORGANIZER_EMAIL, BURROW_ORGANIZER_PASSWORD, BURROW_REPORTS (yes|no). Also BURROW_SERVER_DIR, BURROW_HTTP_PORT
# (home network: the app's port, 8082), BURROW_BIND (listen on one address only), BURROW_PROJECT (Docker name).
set -euo pipefail

VERSION="1.0"
BOX_SHA256="8e19a9453ca7db04df23e5a9f375aadcd0b4c4d155e930a06bbaa68850a5ee46"
BASE="${BURROW_SERVER_BASE:-https://burrowmap.com/server}"
DESK="${BURROW_DESK_UPSTREAM:-https://burrowmap.com}"
PY_IMAGE="python:3.12-slim"
CADDY_IMAGE="caddy:2.8.4-alpine"

say() { printf '%s\n' "$*"; }
die() { printf '\nBurrow Server: %s\n' "$*" >&2; [ "${INSTALLING:-}" = 1 ] && rollback; exit 1; }
rollback() {   # a failed install leaves nothing behind, so running the installer again starts clean
    INSTALLING=0
    say "Undoing the unfinished install..." >&2
    (cd "$DIR" && $DOCKER compose down --remove-orphans) >/dev/null 2>&1 || true
    [ -d "$DIR/data" ] && $DOCKER run --rm --network none -v "$DIR:/d" "$PY_IMAGE" rm -rf /d/data /d/backups /d/caddy >/dev/null 2>&1 || true
    rm -rf "$DIR/data" "$DIR/backups" "$DIR/caddy" "$DIR/compose.yml" "$DIR/Caddyfile" "$DIR/reports.caddy" "$DIR/backup.py" \
           "$DIR/box.py" "$DIR/box.py.new" "$DIR/burrow-server" "$DIR/server.conf" 2>/dev/null || true
    rmdir "$DIR" 2>/dev/null || true
}
tty_ok() { [ -r /dev/tty ] && [ -w /dev/tty ] && : >/dev/tty 2>/dev/null; }
# ask VAR "question" [default]: from the environment if set, else typed (from the terminal, also when piped from curl)
ask() {
    local var=$1 q=$2 def=${3:-} v
    if [ -n "${!var:-}" ]; then return; fi
    tty_ok || die "no terminal to ask \"$q\" on; set $var and run again"
    if [ -n "$def" ]; then printf '%s [%s] ' "$q" "$def" >/dev/tty; else printf '%s ' "$q" >/dev/tty; fi
    IFS= read -r v </dev/tty || true
    printf -v "$var" '%s' "${v:-$def}"
}
ask_secret() {
    local var=$1 q=$2 a b
    if [ -n "${!var:-}" ]; then return; fi
    tty_ok || die "no terminal to ask for a password on; set $var and run again"
    while :; do
        printf '%s ' "$q" >/dev/tty; IFS= read -rs a </dev/tty || true; printf '\n' >/dev/tty
        if [ ${#a} -lt 8 ]; then say "  At least 8 characters, please." >/dev/tty; continue; fi
        printf 'Type it again: ' >/dev/tty; IFS= read -rs b </dev/tty || true; printf '\n' >/dev/tty
        if [ "$a" = "$b" ]; then printf -v "$var" '%s' "$a"; return; fi
        say "  Those didn't match. Once more." >/dev/tty
    done
}
yes_no() { case "$(printf '%s' "$1" | tr 'A-Z' 'a-z')" in ""|y|yes|on|true|1) echo yes ;; *) echo no ;; esac; }
fetch() { curl -fsSL --proto '=https,http,file' --retry 2 -A "BurrowServer/$VERSION" "$1" -o "$2"; }

# ---------- Docker ----------

find_docker() {
    if docker info >/dev/null 2>&1; then DOCKER=docker
    elif command -v sudo >/dev/null && sudo docker info >/dev/null 2>&1; then DOCKER="sudo docker"
    else return 1; fi
    $DOCKER compose version >/dev/null 2>&1 || die "Docker is here but its compose plugin isn't. Install Docker's own packages (https://docs.docker.com/engine/install/) and run this again."
}

get_docker() {
    find_docker && return
    command -v docker >/dev/null && die "Docker is installed but not running, or you can't use it. Start it (sudo systemctl start docker) or add yourself to the docker group, then run this again."
    local go="${BURROW_INSTALL_DOCKER:-}"
    ask go "Docker isn't installed. Install it now with Docker's own script (get.docker.com)? (Y/n)" Y
    [ "$(yes_no "$go")" = yes ] || die "Burrow Server needs Docker. Install it and run this again."
    local t; t=$(mktemp)
    fetch https://get.docker.com "$t"
    if [ "$(id -u)" = 0 ]; then sh "$t"; else sudo sh "$t"; fi
    rm -f "$t"
    find_docker || die "Docker was installed but isn't answering yet. Run this again in a minute."
}

# ---------- the files in the server's folder ----------

write_compose() {
    local ports
    if [ "$MODE" = home ]; then
        local b=""; [ -n "$BIND" ] && b="$BIND:"
        ports="      - \"${b}${PORT}:8082\""
        [ "$PORT" = 8082 ] && ports="$ports
      - \"${b}8096:8096\""
    else
        local b=""; [ -n "$BIND" ] && b="$BIND:"
        ports="      - \"${b}80:80\"
      - \"${b}443:443\"
      - \"${b}443:443/udp\""
    fi
    cat >"$DIR/compose.yml" <<EOF
# Burrow Server $VERSION (written by burrow-server; changes here are replaced by "burrow-server update")
name: $PROJECT
services:
  burrow:
    image: $PY_IMAGE
    command: ["python3", "-I", "/app/box.py"]
    environment:
      BOX_DATA: /data
      BOX_PORT: "8082"
    volumes:
      - ./box.py:/app/box.py:ro
      - ./data:/data
    user: "$BOX_UID:$BOX_UID"
    read_only: true
    tmpfs: ["/tmp:size=64m"]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    pids_limit: 200
    mem_limit: 256m
    networks: [inside]
    restart: unless-stopped
    logging: {driver: json-file, options: {max-size: "5m", max-file: "2"}}
  caddy:
    image: $CADDY_IMAGE
    ports:
$ports
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - ./reports.caddy:/etc/caddy/reports.caddy:ro
      - ./caddy/data:/data
      - ./caddy/config:/config
    cap_drop: [ALL]
    cap_add: [NET_BIND_SERVICE, DAC_OVERRIDE]
    security_opt: ["no-new-privileges:true"]
    networks: [inside, outside]
    restart: unless-stopped
    logging: {driver: json-file, options: {max-size: "5m", max-file: "2"}}
  backup:
    image: $PY_IMAGE
    command: ["python3", "-I", "/app/backup.py"]
    volumes:
      - ./backup.py:/app/backup.py:ro
      - ./data:/data
      - ./backups:/backups
    user: "$BOX_UID:$BOX_UID"
    read_only: true
    tmpfs: ["/tmp:size=16m"]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    network_mode: none
    restart: unless-stopped
    logging: {driver: json-file, options: {max-size: "1m", max-file: "2"}}
networks:
  inside:
    internal: true
  outside: {}
EOF
}

write_caddy() {
    local site
    if [ "$MODE" = home ]; then
        site=":8082 {
	import burrow
}"
        [ "$PORT" = 8082 ] && site="$site
:8096 {
	import burrow
}"
    else
        site="$DOMAIN {
	import burrow
}"
    fi
    cat >"$DIR/Caddyfile" <<EOF
# Burrow Server $VERSION (written by burrow-server; changes here are replaced by "burrow-server update")
{
	admin off
}

(burrow) {
	# Bug reports and app stats from the family's phones: on to the Burrow team, or not (reports.caddy, "burrow-server
	# reports on|off"). Bug reports are sealed on the phone so only the Burrow team can open them.
	@desk path /report /stats
	handle @desk {
		import /etc/caddy/reports.caddy
	}
	handle /api/* {
		reverse_proxy burrow:8082
	}
	handle {
		header Content-Type "text/plain; charset=utf-8"
		respond "This is a Burrow family server. In the Burrow app, choose My own server and type this address." 200
	}
}

$site
EOF
}

write_reports() {
    if [ "$REPORTS" = yes ]; then
        cat >"$DIR/reports.caddy" <<EOF
# on: passed to the Burrow team's desk ($DESK), without the phone's address
rewrite * /cloud/desk{path}
reverse_proxy $DESK {
	header_up Host {upstream_hostport}
	header_up -X-Forwarded-For
	header_up -X-Forwarded-Host
	header_up -X-Real-Ip
}
EOF
    else
        cat >"$DIR/reports.caddy" <<'EOF'
# off
header Content-Type "text/plain; charset=utf-8"
respond "This family's Burrow server is set not to send bug reports to the Burrow team." 403
EOF
    fi
}

write_backup() {
    cat >"$DIR/backup.py" <<'EOF'
"""Burrow Server's backup: a copy of the family's data every night (backups/box-YYYY-MM-DD.db), the newest 7 kept.
'python3 backup.py now' makes one at once."""
import datetime, glob, os, sqlite3, sys, time


def once():
    if not os.path.exists("/data/box.db"):
        return None
    out = "/backups/box-%s.db" % datetime.date.today().isoformat()
    a, b = sqlite3.connect("/data/box.db"), sqlite3.connect(out + ".part")
    with b:
        a.backup(b)
    a.close(); b.close()
    os.chmod(out + ".part", 0o600); os.replace(out + ".part", out)
    for old in sorted(glob.glob("/backups/box-*.db"))[:-7]:
        os.remove(old)
    return out


if __name__ == "__main__":
    if sys.argv[1:] == ["now"]:
        print(once() or "nothing to back up yet", flush=True); sys.exit()
    time.sleep(600)
    while True:
        try: print("backup:", once(), flush=True)
        except Exception as e: print("backup failed:", e, flush=True)
        time.sleep(86400)
EOF
}

save_conf() {
    cat >"$DIR/server.conf" <<EOF
# Burrow Server settings (read by burrow-server)
MODE=$MODE
DOMAIN=$DOMAIN
PORT=$PORT
BIND=$BIND
PROJECT=$PROJECT
REPORTS=$REPORTS
BOX_UID=$BOX_UID
DOCKER="$DOCKER"
DESK=$DESK
INSTALLED_VERSION=$VERSION
EOF
}

get_box() {   # box.py from BASE, checked against the SHA-256 this script was published with
    local t="$DIR/box.py.new"
    fetch "$BASE/box.py" "$t" || die "couldn't download the server from $BASE/box.py"
    local got; got=$(sha256sum "$t" | cut -d' ' -f1)
    if [ "$got" != "$BOX_SHA256" ]; then rm -f "$t"; die "the downloaded server didn't match its checksum, so it wasn't used. Try again later."; fi
    chmod 644 "$t"; mv "$t" "$DIR/box.py"
}

get_self() {   # this script, kept in the folder as the burrow-server command
    if [ -f "${BASH_SOURCE[0]:-}" ] && [ "$(basename "${BASH_SOURCE[0]}")" != burrow-server ]; then cp "${BASH_SOURCE[0]}" "$DIR/burrow-server"
    elif [ ! -f "$DIR/burrow-server" ] || [ "${1:-}" = fresh ]; then fetch "$BASE/install.sh" "$DIR/burrow-server"; fi
    chmod 755 "$DIR/burrow-server"
}

dc() { (cd "$DIR" && $DOCKER compose "$@"); }

wait_box() {
    local i
    for i in $(seq 1 60); do
        dc exec -T burrow python3 -I -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8082/api/server', timeout=2)" >/dev/null 2>&1 && return
        sleep 1
    done
    die "the server didn't start. See: cd $DIR && $DOCKER compose logs burrow"
}

make_organizer() {   # the first account is the family's organizer; the password goes in on standard input, never on a command line
    printf '%s\n%s\n%s\n' "$BURROW_ORGANIZER_NAME" "$(printf '%s' "$BURROW_ORGANIZER_EMAIL" | tr 'A-Z' 'a-z')" "$BURROW_ORGANIZER_PASSWORD" \
        | dc exec -T burrow python3 -I -c '
import json, sys, urllib.request, urllib.parse, urllib.error
n, e, p = sys.stdin.read().split("\n")[:3]
d = {"name": n.strip(), "email": e.strip(), "password": p}; B = "http://127.0.0.1:8082"; jar = {}
def go(method, path, js=None, form=None):   # the box marks its cookie https-only, so it is carried by hand here
    data = json.dumps(js).encode() if js is not None else urllib.parse.urlencode(form).encode()
    h = {"Content-Type": "application/json" if js is not None else "application/x-www-form-urlencoded"}
    if jar: h["Cookie"] = "JSESSIONID=" + jar["s"]
    try:
        with urllib.request.urlopen(urllib.request.Request(B + path, data=data, method=method, headers=h)) as r:
            c = r.headers.get("Set-Cookie", "")
            if c.startswith("JSESSIONID="): jar["s"] = c.split(";")[0].split("=", 1)[1]
            return r.status
    except urllib.error.HTTPError as e:
        sys.exit("%s %s: %s" % (path, e.code, e.read().decode(errors="replace")[:200]))
go("POST", "/api/users", {"name": d["name"], "email": d["email"], "password": d["password"]})
go("POST", "/api/session", form={"email": d["email"], "password": d["password"]})
go("POST", "/api/groups", {"name": "Family"})
'
}

addresses() {
    if [ "$MODE" = domain ]; then say "  https://$DOMAIN"; return; fi
    local ip ts
    ip=$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<NF;i++) if($i=="src"){print $(i+1); exit}}')
    [ -n "$BIND" ] && ip=$BIND
    [ -n "$ip" ] && say "  http://$ip:$PORT        (at home)"
    if command -v tailscale >/dev/null && ts=$(tailscale ip -4 2>/dev/null | head -1) && [ -n "$ts" ] && [ "$ts" != "$ip" ]; then
        say "  http://$ts:$PORT        (anywhere, on phones that use Tailscale)"
    fi
}

# ---------- commands ----------

load() {
    [ -f "$DIR/server.conf" ] || die "no Burrow Server in $DIR (set BURROW_SERVER_DIR if it's somewhere else)"
    # shellcheck disable=SC1091
    . "$DIR/server.conf"
}

install() {
    [ "$(uname -s)" = Linux ] || die "this installer is for Linux. A Windows and Mac app is on the way."
    command -v curl >/dev/null || die "curl is needed (sudo apt install curl)"
    if [ -f "$DIR/server.conf" ]; then say "Burrow Server is already installed in $DIR."; say "  $DIR/burrow-server status   (or update)"; exit 0; fi
    say ""
    say "Burrow Server $VERSION: your family's own Burrow server."
    say ""
    get_docker

    say ""
    say "Where will the family's phones reach this server?"
    say "  1) A web address you own (like family.example.com) that points at this computer, with ports 80 and 443"
    say "     open to the internet. Phones work anywhere, over https."
    say "  2) Home network only. Phones work at home, or anywhere if this computer and the phones use Tailscale."
    local where="${BURROW_ADDRESS:-}"
    if [ -z "$where" ]; then
        ask where "Choose 1 or 2:" 2
        if [ "$where" = 1 ]; then where=""; ask where "The web address (just the name, like family.example.com):"; else where=home; fi
    fi
    where=$(printf '%s' "$where" | tr 'A-Z' 'a-z' | sed -e 's#^https\?://##' -e 's#/.*$##')
    if [ "$where" = home ] || [ "$where" = 2 ]; then MODE=home; DOMAIN=""
    else
        printf '%s' "$where" | grep -Eq '^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$' || die "\"$where\" isn't a web address like family.example.com"
        MODE=domain; DOMAIN=$where
    fi

    say ""
    say "The organizer's account (the person who adds the rest of the family in the app):"
    ask BURROW_ORGANIZER_NAME "  Your name:"
    ask BURROW_ORGANIZER_EMAIL "  Your email (it's only your sign-in; nothing is sent to it):"
    ask_secret BURROW_ORGANIZER_PASSWORD "  A password for the app (8 or more characters):"
    [ -n "$BURROW_ORGANIZER_NAME" ] || die "a name is needed"
    printf '%s' "$BURROW_ORGANIZER_EMAIL" | grep -Eq '^[^@ ]+@[^@ ]+\.[^@ ]+$' || die "\"$BURROW_ORGANIZER_EMAIL\" doesn't look like an email address"

    say ""
    say "When something goes wrong in the app, the family can send a bug report to the Burrow team. Reports are sealed"
    say "on the phone so only the Burrow team can read them (not even this server). The app also sends counts, like how"
    say "often it checked for news, never locations. You can change this later: burrow-server reports on|off"
    local rep="${BURROW_REPORTS:-}"
    ask rep "Send bug reports and app stats to the Burrow team? (Y/n)" Y
    REPORTS=$(yes_no "$rep")

    PORT=${BURROW_HTTP_PORT:-8082}; BIND=${BURROW_BIND:-}; PROJECT=${BURROW_PROJECT:-burrow-server}
    if [ "$(id -u)" = 0 ]; then BOX_UID=10001; else BOX_UID=$(id -u); fi

    say ""
    say "Setting up in $DIR ..."
    INSTALLING=1
    mkdir -p "$DIR/data" "$DIR/backups" "$DIR/caddy/data" "$DIR/caddy/config"
    chmod 700 "$DIR/data" "$DIR/backups"
    [ "$BOX_UID" = 10001 ] && chown "$BOX_UID:$BOX_UID" "$DIR/data" "$DIR/backups"
    get_box; get_self; write_compose; write_caddy; write_reports; write_backup
    # the server first, on its own: the organizer's account is made before anything outside can reach it
    dc up -d --quiet-pull burrow backup || die "Docker couldn't start the server (see above)"
    wait_box
    make_organizer >/dev/null || die "the organizer's account wasn't made (see above)"
    unset BURROW_ORGANIZER_PASSWORD
    dc up -d --quiet-pull caddy || die "Docker couldn't start the front door, Caddy (see above)"
    save_conf; INSTALLING=0

    say ""
    say "Burrow Server is running."
    say ""
    say "On each phone: install Burrow from https://burrowmap.com, then Sign in > My own server, with this address:"
    addresses
    say "You sign in with $BURROW_ORGANIZER_EMAIL and your password, then add everyone else from the app."
    [ "$MODE" = domain ] && say "(The https certificate for $DOMAIN takes a minute or two the first time; ports 80 and 443 must reach this computer.)"
    say ""
    say "Manage it with: $DIR/burrow-server status | reports on|off | backup | update | stop | start | uninstall"
}

status() {
    load
    dc ps --format "table {{.Service}}\t{{.State}}\t{{.Status}}"
    say ""; say "Bug reports to the Burrow team: $REPORTS"; say "Address for the app:"; addresses
    local n; n=$(ls "$DIR/backups"/box-*.db 2>/dev/null | wc -l); say "Backups kept: $n (in $DIR/backups)"
}

reports() {
    load
    case "${1:-}" in on|yes) REPORTS=yes ;; off|no) REPORTS=no ;; *) die "use: burrow-server reports on|off" ;; esac
    write_reports; save_conf; dc restart caddy >/dev/null 2>&1
    say "Bug reports and app stats to the Burrow team: $REPORTS"
}

update() {   # the newest install.sh fetches the newest box.py (checked) and rewrites the files; data and settings stay
    load
    local t; t=$(mktemp)
    fetch "$BASE/install.sh" "$t" || die "couldn't reach $BASE"
    BURROW_SERVER_DIR="$DIR" bash "$t" _refresh; rm -f "$t"
}

refresh() {
    load
    get_box; cp "${BASH_SOURCE[0]}" "$DIR/burrow-server.new" && chmod 755 "$DIR/burrow-server.new" && mv "$DIR/burrow-server.new" "$DIR/burrow-server"
    write_compose; write_caddy; write_reports; write_backup; save_conf
    # recreated, not just restarted: a replaced file (box.py) only reaches a container through a fresh mount
    dc pull --quiet >/dev/null 2>&1 || true
    dc up -d --force-recreate --remove-orphans >/dev/null 2>&1 || die "Docker couldn't start the new version (cd $DIR && $DOCKER compose up -d)"
    wait_box
    say "Burrow Server is now $VERSION."
}

backup_now() { load; dc exec -T backup python3 -I /app/backup.py now; }

uninstall() {
    load
    dc down --remove-orphans
    if [ "${1:-}" = --delete-data ]; then
        local sure="${BURROW_ASSUME_YES:-}"
        ask sure "Delete the family's data and backups in $DIR for good? Type DELETE to confirm:"
        [ "$sure" = DELETE ] || die "nothing deleted"
        $DOCKER run --rm -v "$DIR:/d" "$PY_IMAGE" rm -rf /d/data /d/backups /d/caddy
        rm -rf "$DIR"
        say "Burrow Server and its data are removed."
    else
        say "Burrow Server is stopped and removed. The family's data stays in $DIR/data (and backups in $DIR/backups)."
    fi
}

if [ -n "${BURROW_SERVER_DIR:-}" ]; then DIR=$BURROW_SERVER_DIR
elif [ "$(basename "${BASH_SOURCE[0]:-x}")" = burrow-server ]; then DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
elif [ "$(id -u)" = 0 ]; then DIR=/opt/burrow-server
else DIR=$HOME/burrow-server; fi

case "${1:-install}" in
    install) DOCKER=docker; install ;;
    status) status ;;
    reports) reports "${2:-}" ;;
    backup) backup_now ;;
    update) update ;;
    _refresh) refresh ;;
    stop) load; dc stop ;;
    start) load; dc up -d ;;
    uninstall) uninstall "${2:-}" ;;
    *) say "use: burrow-server status | reports on|off | backup | update | stop | start | uninstall [--delete-data]"; exit 2 ;;
esac
