#!/usr/bin/env bash
# brooog-ikev2.sh - your own IKEv2 VPN server (strongSwan), ready for the IKEv2 VPN app on
# iPhone, iPad, Mac, Android and Windows. https://brooog.com/ikev2
#
# Ubuntu 20.04+ or Debian 11+, run as root on a fresh server:
#   bash brooog-ikev2.sh                                   asks for what it needs
#   bash brooog-ikev2.sh --host vpn.example.com --email you@example.com --user alice
#
# Certificates:
#   a domain name pointing at this server -> a free Let's Encrypt certificate: every device
#                                            trusts it, nothing to install (recommended)
#   an IP address (or --own-ca)           -> its own certificate authority: install ca.cer /
#                                            ca.crt on each device once (the files are made for you)
#
# After installing:
#   bash brooog-ikev2.sh --add-user NAME [PASSWORD]   another login (a random password if none)
#   bash brooog-ikev2.sh --del-user NAME              remove a login
#   bash brooog-ikev2.sh --users                      the logins
#   bash brooog-ikev2.sh --show                       server, logins and files for the apps
#   bash brooog-ikev2.sh --share                      a 10-minute download link for the
#                                                     certificate files (for phones and PCs)
#   bash brooog-ikev2.sh --status                     is it running, who is connected
#   bash brooog-ikev2.sh --uninstall                  remove everything this script added
#
# Options for the install:
#   --host NAME|IP   the address the apps connect to (default: asks; suggests this server's IP)
#   --email ADDR     for Let's Encrypt expiry notices (optional)
#   --user NAME      the first login (default: vpnuser), --password PW (default: random)
#   --dns A,B        DNS servers for connected devices (default: 1.1.1.1,8.8.8.8)
#   --pool CIDR      addresses for connected devices (default: 10.10.10.0/24)
#   --own-ca         use its own certificate authority even with a domain name
#   --yes            no questions (needs --host)
#
# Privacy: strongSwan logs no connection details (who, from where, when).
set -euo pipefail

SELF=/usr/local/sbin/brooog-ikev2
CONF=/etc/brooog-ikev2.conf
SW=/etc/swanctl
USERS=$SW/conf.d/brooog-users.conf
CLIENT=/root/ikev2-client
FWNAME=brooog-ikev2
VERSION=1.0

c_ok=$'\e[32m'; c_warn=$'\e[33m'; c_err=$'\e[31m'; c_b=$'\e[1m'; c_0=$'\e[0m'
say()  { echo "${c_b}==>${c_0} $*"; }
ok()   { echo "${c_ok}✓${c_0} $*"; }
warn() { echo "${c_warn}!${c_0} $*" >&2; }
die()  { echo "${c_err}✗ $*${c_0}" >&2; exit 1; }

[[ $EUID -eq 0 ]] || die "run as root: sudo bash $0 $*"

# ------------------------------------------------------------------ settings
HOST=""; EMAIL=""; FIRST_USER="vpnuser"; FIRST_PW=""; DNS="1.1.1.1,8.8.8.8"
POOL="10.10.10.0/24"; OWN_CA=0; YES=0; CERT=""
load_conf() { [[ -f $CONF ]] && . "$CONF" || true; }
save_conf() {
    umask 077
    cat > "$CONF" <<EOF
# brooog-ikev2 $VERSION
HOST="$HOST"
CERT="$CERT"
POOL="$POOL"
DNS="$DNS"
IFACE="$IFACE"
EOF
}

is_ip() { [[ $1 =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; }
public_ip() {
    curl -4 -fsS --max-time 8 https://api.ipify.org 2>/dev/null \
      || curl -4 -fsS --max-time 8 https://ifconfig.co 2>/dev/null \
      || ip -4 route get 1.1.1.1 | awk '{for(i=1;i<=NF;i++) if($i=="src") print $(i+1)}'
}
default_iface() { ip -4 route show default | awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1); exit}}'; }
random_pw() { local s; s=$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9'); echo "${s:0:20}"; }
valid_user() { [[ $1 =~ ^[A-Za-z0-9._@-]{1,64}$ ]]; }

# ------------------------------------------------------------------ users
# One file, rewritten whole: secrets { eap-<name> { id = <name>  secret = "<pw>" } }
users_list() { [[ -f $USERS ]] && sed -n 's/^ *id = "\(.*\)"$/\1/p' "$USERS" || true; }
users_write() {   # stdin: "name<TAB>password" lines
    local tmp; tmp=$(mktemp)
    { echo "# brooog-ikev2: the logins (bash brooog-ikev2.sh --add-user / --del-user)"
      echo "secrets {"
      local n=0 name pw
      while IFS=$'\t' read -r name pw; do
          [[ -n $name ]] || continue
          n=$((n + 1))
          printf '    eap-%d {\n        id = "%s"\n        secret = "%s"\n    }\n' "$n" "$name" "$pw"
      done
      echo "}"; } > "$tmp"
    install -m 600 "$tmp" "$USERS"; rm -f "$tmp"
}
users_pairs() {   # name<TAB>password of every login
    [[ -f $USERS ]] || return 0
    awk '/id = "/ {gsub(/.*id = "|"$/, ""); id=$0} /secret = "/ {gsub(/.*secret = "|"$/, ""); print id "\t" $0}' "$USERS"
}
reload_creds() { swanctl --load-creds --clear >/dev/null 2>&1 || swanctl --load-creds >/dev/null; }

add_user() {
    local name=$1 pw=${2:-}
    valid_user "$name" || die "login names: letters, digits, . _ @ - (up to 64)"
    [[ -n $pw ]] || pw=$(random_pw)
    [[ $pw != *'"'* && $pw != *'\'* ]] || die "the password can't contain \" or \\"
    { users_pairs | awk -F'\t' -v n="$name" '$1 != n'; printf '%s\t%s\n' "$name" "$pw"; } | users_write
    reload_creds
    ok "login ${c_b}$name${c_0} / password ${c_b}$pw${c_0}"
}
del_user() {
    users_list | grep -qxF -- "$1" || die "no login called $1"
    users_pairs | awk -F'\t' -v n="$1" '$1 != n' | users_write
    reload_creds
    swanctl --list-sas 2>/dev/null | grep -q "'$1'" && warn "$1 is still connected until it reconnects"
    ok "removed $1"
}

# ------------------------------------------------------------------ firewall
# Own rules, tagged with a comment; a small service puts them back at every boot (after ufw /
# netfilter-persistent), so they work next to whatever firewall the server already has.
write_firewall() {
    cat > /usr/local/sbin/$FWNAME-fw <<'EOF'
#!/usr/bin/env bash
# brooog-ikev2 firewall: IKEv2 in, NAT out for the VPN devices. --off removes the rules.
. /etc/brooog-ikev2.conf
TAG=brooog-ikev2
rule() {   # rule <table> <chain> <args...>: add once, at the top
    local t=$1 c=$2; shift 2
    iptables -t "$t" -C "$c" "$@" -m comment --comment $TAG 2>/dev/null \
      || iptables -t "$t" -I "$c" 1 "$@" -m comment --comment $TAG
}
off() {
    for t in filter nat mangle; do
        iptables -t $t -S 2>/dev/null | grep -- "--comment $TAG" | sed 's/^-A/-D/' | while read -r r; do
            eval iptables -t $t $r 2>/dev/null || true
        done
    done
}
if [[ ${1:-} == --off ]]; then off; exit 0; fi
IF=${IFACE:-$(ip -4 route show default | awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1); exit}}')}
rule filter INPUT -p udp --dport 500 -j ACCEPT
rule filter INPUT -p udp --dport 4500 -j ACCEPT
rule filter INPUT -p esp -j ACCEPT
rule filter FORWARD -d "$POOL" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
rule filter FORWARD -s "$POOL" -m policy --dir in --pol ipsec -j ACCEPT
rule mangle FORWARD -s "$POOL" -o "$IF" -p tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360
rule nat POSTROUTING -s "$POOL" -o "$IF" -m policy --dir out --pol none -j MASQUERADE
EOF
    chmod 700 /usr/local/sbin/$FWNAME-fw
    cat > /etc/systemd/system/$FWNAME-fw.service <<EOF
[Unit]
Description=brooog-ikev2 firewall rules (IKEv2 in, NAT for VPN devices)
After=network-online.target ufw.service netfilter-persistent.service firewalld.service
Wants=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/$FWNAME-fw
ExecStop=/usr/local/sbin/$FWNAME-fw --off
[Install]
WantedBy=multi-user.target
EOF
    cat > /etc/sysctl.d/90-brooog-ikev2.conf <<'EOF'
# brooog-ikev2: forward the VPN devices' traffic
net.ipv4.ip_forward = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.ip_no_pmtu_disc = 1
EOF
    sysctl -q -p /etc/sysctl.d/90-brooog-ikev2.conf
    systemctl daemon-reload
    systemctl enable $FWNAME-fw.service >/dev/null 2>&1
    systemctl restart $FWNAME-fw.service
}

# ------------------------------------------------------------------ certificates
cert_letsencrypt() {
    say "Let's Encrypt certificate for $HOST (port 80 opens for a moment)"
    command -v certbot >/dev/null || apt-get install -y -qq certbot >/dev/null
    mkdir -p /etc/letsencrypt/renewal-hooks/{pre,post,deploy}
    cat > /etc/letsencrypt/renewal-hooks/pre/$FWNAME.sh <<'EOF'
#!/bin/sh
iptables -C INPUT -p tcp --dport 80 -m comment --comment brooog-ikev2-acme -j ACCEPT 2>/dev/null \
  || iptables -I INPUT 1 -p tcp --dport 80 -m comment --comment brooog-ikev2-acme -j ACCEPT
EOF
    cat > /etc/letsencrypt/renewal-hooks/post/$FWNAME.sh <<'EOF'
#!/bin/sh
iptables -D INPUT -p tcp --dport 80 -m comment --comment brooog-ikev2-acme -j ACCEPT 2>/dev/null || true
EOF
    cat > /etc/letsencrypt/renewal-hooks/deploy/$FWNAME.sh <<EOF
#!/bin/sh
# brooog-ikev2: the renewed certificate into strongSwan
. $CONF
L=/etc/letsencrypt/live/\$HOST
[ -f "\$L/cert.pem" ] || exit 0
install -m 644 "\$L/cert.pem"  $SW/x509/server.crt
install -m 644 "\$L/chain.pem" $SW/x509ca/letsencrypt-chain.crt
install -m 600 "\$L/privkey.pem" $SW/private/server.key
swanctl --load-creds >/dev/null 2>&1 || true
EOF
    chmod 755 /etc/letsencrypt/renewal-hooks/{pre,post,deploy}/$FWNAME.sh
    sh /etc/letsencrypt/renewal-hooks/pre/$FWNAME.sh
    local mail=(--register-unsafely-without-email)
    [[ -n $EMAIL ]] && mail=(-m "$EMAIL")
    if certbot certonly --standalone --non-interactive --agree-tos "${mail[@]}" \
            --key-type rsa --rsa-key-size 2048 -d "$HOST" >/tmp/$FWNAME-certbot.log 2>&1; then
        sh /etc/letsencrypt/renewal-hooks/post/$FWNAME.sh
        RENEWED_LINEAGE=/etc/letsencrypt/live/$HOST sh /etc/letsencrypt/renewal-hooks/deploy/$FWNAME.sh
        CERT=letsencrypt
        ok "certificate from Let's Encrypt (renews by itself)"
        return 0
    fi
    sh /etc/letsencrypt/renewal-hooks/post/$FWNAME.sh
    warn "Let's Encrypt didn't work (see /tmp/$FWNAME-certbot.log): is $HOST pointing at this server,"
    warn "and is TCP port 80 open in your provider's firewall? Using its own certificate authority instead."
    return 1
}

cert_own_ca() {
    say "Own certificate authority for $HOST"
    command -v pki >/dev/null || apt-get install -y -qq strongswan-pki >/dev/null
    local san=(--san "$HOST")
    is_ip "$HOST" && san=(--san "$HOST" --san "@$HOST")
    if [[ ! -f $SW/private/ca.key ]]; then
        pki --gen --type rsa --size 3072 --outform pem > $SW/private/ca.key 2>/dev/null
        pki --self --ca --lifetime 3650 --in $SW/private/ca.key --type rsa \
            --dn "CN=IKEv2 VPN CA ($HOST)" --outform pem > $SW/x509ca/ca.crt 2>/dev/null
    fi
    pki --gen --type rsa --size 3072 --outform pem > $SW/private/server.key 2>/dev/null
    # serverAuth + "IP security IKE intermediate": what Windows and macOS look for
    pki --pub --in $SW/private/server.key --type rsa 2>/dev/null \
      | pki --issue --lifetime 3650 --cacert $SW/x509ca/ca.crt --cakey $SW/private/ca.key \
            --dn "CN=$HOST" "${san[@]}" --flag serverAuth --flag ikeIntermediate --outform pem 2>/dev/null \
      > $SW/x509/server.crt
    openssl x509 -in $SW/x509/server.crt -noout 2>/dev/null || die "couldn't make the server certificate"
    chmod 600 $SW/private/*.key
    CERT=own-ca
    ok "certificate made (valid 10 years); install ca.cer / ca.crt on each device once"
}

# ------------------------------------------------------------------ strongSwan
write_swanctl() {
    local local_id=$HOST
    cat > $SW/conf.d/brooog-ikev2.conf <<EOF
# brooog-ikev2 $VERSION - IKEv2 with a login (EAP-MSCHAPv2) and the server's certificate.
# Works with the IKEv2 VPN app (iPhone, iPad, Mac, Android, Windows) and the built-in clients.
connections {
    brooog-ikev2 {
        version = 2
        # newest first; aes256-sha256-modp2048 is what the Windows script sets up
        proposals = aes256gcm16-prfsha384-ecp384,aes256gcm16-prfsha256-ecp256,aes256-sha256-ecp256,aes256-sha256-modp2048,aes128-sha256-modp2048,aes256-sha384-modp2048
        pools = brooog-pool
        send_cert = always
        fragmentation = yes
        unique = never
        dpd_delay = 30s
        rekey_time = 0s
        local {
            auth = pubkey
            certs = server.crt
            id = $local_id
        }
        remote {
            auth = eap-mschapv2
            eap_id = %any
        }
        children {
            brooog-ikev2 {
                local_ts = 0.0.0.0/0
                esp_proposals = aes256gcm16,aes128gcm16,aes256-sha256,aes128-sha256,aes256-sha1
                rekey_time = 0s
                dpd_action = clear
            }
        }
    }
}
pools {
    brooog-pool {
        addrs = $POOL
        dns = $DNS
    }
}
EOF
    # no connection logs (who, from where, when): errors only, nothing kept
    cat > /etc/strongswan.d/zz-brooog-nolog.conf <<'EOF'
charon {
    filelog { }
    syslog {
        daemon {
            default = -1
            ike = 0
        }
        auth {
            default = -1
        }
    }
}
charon-systemd {
    journal {
        default = -1
        ike = 0
    }
}
EOF
}

sw_service() {
    for u in strongswan strongswan-swanctl; do
        systemctl list-unit-files "$u.service" >/dev/null 2>&1 && systemctl cat "$u.service" >/dev/null 2>&1 && { echo "$u"; return; }
    done
    echo strongswan
}

# ------------------------------------------------------------------ files for the apps
write_client_files() {
    mkdir -p "$CLIENT"; chmod 700 "$CLIENT"
    rm -f "$CLIENT"/ca.crt "$CLIENT"/ca.cer
    if [[ $CERT == own-ca ]]; then
        cp $SW/x509ca/ca.crt "$CLIENT/ca.crt"
        openssl x509 -in $SW/x509ca/ca.crt -outform der -out "$CLIENT/ca.cer"
    fi
    local import=""
    [[ $CERT == own-ca ]] && import='
# the server uses its own certificate authority: trust it on this PC (once)
$ca = Join-Path $PSScriptRoot "ca.cer"
if (Test-Path $ca) { Import-Certificate -FilePath $ca -CertStoreLocation Cert:\LocalMachine\Root | Out-Null; Write-Host "Certificate installed." }
else { Write-Warning "ca.cer not found next to this script: download it too." }'
    cat > "$CLIENT/windows-setup.ps1" <<EOF
# IKEv2 VPN for Windows' built-in VPN (Settings > Network > VPN). Not needed with the IKEv2 VPN app.
# Right-click PowerShell > Run as administrator, then:  powershell -ExecutionPolicy Bypass -File .\\windows-setup.ps1
\$Server = "$HOST"
\$Name = "IKEv2 VPN ($HOST)"
$import
Remove-VpnConnection -Name \$Name -Force -AllUserConnection -ErrorAction SilentlyContinue
Add-VpnConnection -Name \$Name -ServerAddress \$Server -TunnelType Ikev2 -AuthenticationMethod Eap -EncryptionLevel Required -AllUserConnection -RememberCredential
# stronger than Windows' defaults (and what the server expects)
Set-VpnConnectionIPsecConfiguration -ConnectionName \$Name -AuthenticationTransformConstants GCMAES256 -CipherTransformConstants GCMAES256 -EncryptionMethod AES256 -IntegrityCheckMethod SHA256 -DHGroup Group14 -PfsGroup None -AllUserConnection -Force
Write-Host "Done: Settings > Network & internet > VPN > \$Name > Connect, and sign in with your VPN login."
EOF
    {
        echo "IKEv2 VPN - $HOST"
        echo "Server : $HOST"
        echo "Type   : IKEv2, username and password (EAP-MSCHAPv2)"
        if [[ $CERT == own-ca ]]; then
            echo "Certificate: own certificate authority - install ca.crt (Android, iPhone, Mac) or ca.cer (Windows) once"
            echo "  SHA-256 fingerprint: $(openssl x509 -in $SW/x509ca/ca.crt -noout -fingerprint -sha256 | cut -d= -f2)"
        else
            echo "Certificate: Let's Encrypt - nothing to install"
        fi
        echo; echo "Logins:"; users_pairs | awk -F'\t' '{printf "  %s / %s\n", $1, $2}'
        echo; echo "Guide: https://brooog.com/ikev2"
    } > "$CLIENT/README.txt"
    chmod 600 "$CLIENT"/*
}

show() {
    load_conf
    [[ -n $HOST ]] || die "not installed yet: bash $0"
    echo
    echo "${c_b}Your IKEv2 VPN${c_0}"
    echo "  Server        : ${c_b}$HOST${c_0}"
    echo "  Type          : IKEv2 - username and password (EAP-MSCHAPv2)"
    if [[ $CERT == own-ca ]]; then
        echo "  Certificate   : own certificate authority - install it once on each device:"
        echo "                  $CLIENT/ca.crt (iPhone, iPad, Mac, Android), $CLIENT/ca.cer (Windows)"
        echo "                  fingerprint $(openssl x509 -in $SW/x509ca/ca.crt -noout -fingerprint -sha256 | cut -d= -f2)"
        echo "                  get them on your devices: bash $SELF --share"
    else
        echo "  Certificate   : Let's Encrypt - trusted everywhere, nothing to install"
    fi
    echo "  Logins:"
    users_pairs | awk -F'\t' '{printf "    %s / %s\n", $1, $2}'
    echo
    echo "  In the IKEv2 VPN app: Add VPN > Server: $HOST, your username and password."
    echo "  Windows' own VPN client: $CLIENT/windows-setup.ps1    Guide: https://brooog.com/ikev2"
    echo
}

# --share: the certificate files over a one-off link for 10 minutes (random port and path)
share() {
    load_conf
    [[ -d $CLIENT ]] || die "not installed yet"
    [[ $CERT == own-ca ]] || warn "Let's Encrypt certificate: devices need no file - sharing the Windows script only"
    command -v python3 >/dev/null || apt-get install -y -qq python3 >/dev/null
    local port token dir ip
    port=$(( 20000 + RANDOM % 20000 )); token=$(random_pw); token=${token:0:16}
    dir=$(mktemp -d); mkdir -p "$dir/$token"
    for f in ca.crt ca.cer windows-setup.ps1; do [[ -f $CLIENT/$f ]] && cp "$CLIENT/$f" "$dir/$token/"; done
    ip=$(public_ip)
    iptables -I INPUT 1 -p tcp --dport "$port" -m comment --comment brooog-ikev2-share -j ACCEPT
    trap 'iptables -D INPUT -p tcp --dport '"$port"' -m comment --comment brooog-ikev2-share -j ACCEPT 2>/dev/null; rm -rf '"$dir"'' EXIT
    echo
    echo "Open on the phone or PC (for 10 minutes; Ctrl+C stops it sooner):"
    for f in ca.crt ca.cer windows-setup.ps1; do
        [[ -f $dir/$token/$f ]] && echo "  ${c_b}http://$ip:$port/$token/$f${c_0}"
    done
    [[ $CERT == own-ca ]] && echo "  Check the certificate's SHA-256 fingerprint on the device: $(openssl x509 -in $SW/x509ca/ca.crt -noout -fingerprint -sha256 | cut -d= -f2)"
    echo "  (If it doesn't open, allow TCP $port in your provider's firewall for a moment.)"
    echo
    (cd "$dir" && timeout 600 python3 -m http.server "$port" --bind 0.0.0.0 >/dev/null 2>&1) || true
    ok "sharing stopped"
}

status() {
    load_conf
    local svc; svc=$(sw_service)
    echo "strongSwan : $(systemctl is-active "$svc" 2>/dev/null || echo inactive)"
    echo "firewall   : $(systemctl is-active $FWNAME-fw 2>/dev/null || echo inactive)"
    echo "server     : ${HOST:-?} (${CERT:-?})"
    if [[ $CERT == letsencrypt && -f $SW/x509/server.crt ]]; then
        echo "certificate: until $(openssl x509 -in $SW/x509/server.crt -noout -enddate | cut -d= -f2) (renews by itself)"
    fi
    echo "connected  : $(swanctl --list-sas 2>/dev/null | grep -c 'ESTABLISHED' || true) device(s)"
}

uninstall() {
    load_conf
    say "Removing the IKEv2 VPN set up by this script"
    local svc; svc=$(sw_service)
    systemctl disable --now $FWNAME-fw.service >/dev/null 2>&1 || true
    /usr/local/sbin/$FWNAME-fw --off 2>/dev/null || true
    rm -f /etc/systemd/system/$FWNAME-fw.service /usr/local/sbin/$FWNAME-fw /etc/sysctl.d/90-brooog-ikev2.conf
    rm -f $SW/conf.d/brooog-ikev2.conf "$USERS" /etc/strongswan.d/zz-brooog-nolog.conf
    rm -f $SW/x509/server.crt $SW/private/server.key $SW/x509ca/letsencrypt-chain.crt
    rm -f /etc/letsencrypt/renewal-hooks/{pre,post,deploy}/$FWNAME.sh
    if [[ ${1:-} == --all ]]; then
        rm -f $SW/x509ca/ca.crt $SW/private/ca.key
        apt-get purge -y -qq 'strongswan*' charon-systemd libcharon-extra-plugins libstrongswan-extra-plugins >/dev/null 2>&1 || true
    else
        systemctl restart "$svc" >/dev/null 2>&1 || true
    fi
    rm -rf "$CLIENT"; rm -f "$CONF" "$SELF"
    systemctl daemon-reload
    ok "removed (the certificate authority is kept unless you use --uninstall --all)"
}

# ------------------------------------------------------------------ install
install_vpn() {
    load_conf
    while [[ $# -gt 0 ]]; do
        case $1 in
            --host) HOST=$2; shift 2 ;;
            --email) EMAIL=$2; shift 2 ;;
            --user) FIRST_USER=$2; shift 2 ;;
            --password) FIRST_PW=$2; shift 2 ;;
            --dns) DNS=$2; shift 2 ;;
            --pool) POOL=$2; shift 2 ;;
            --own-ca) OWN_CA=1; shift ;;
            --yes|-y) YES=1; shift ;;
            *) die "unknown option $1 (see the top of this script)" ;;
        esac
    done

    . /etc/os-release 2>/dev/null || true
    [[ ${ID:-} == ubuntu || ${ID:-} == debian || ${ID_LIKE:-} == *debian* ]] \
        || die "this script is for Ubuntu 20.04+ or Debian 11+ (found: ${PRETTY_NAME:-unknown})"
    command -v systemctl >/dev/null || die "systemd is needed"

    IFACE=$(default_iface); [[ -n $IFACE ]] || die "no default network route found"
    local myip; myip=$(public_ip)
    if [[ -z $HOST ]]; then
        [[ $YES -eq 1 ]] && die "--yes needs --host"
        echo "The address your devices connect to: a domain name pointing at this server"
        echo "(best: a free Let's Encrypt certificate, nothing to install on devices) or its IP address."
        read -r -p "Domain name or IP [$myip]: " HOST
        HOST=${HOST:-$myip}
        if ! is_ip "$HOST" && [[ -z $EMAIL ]]; then
            read -r -p "Email for Let's Encrypt notices (optional): " EMAIL
        fi
    fi
    HOST=${HOST,,}
    [[ $HOST =~ ^[a-z0-9.-]+$ ]] || die "not a valid domain name or IP: $HOST"
    valid_user "$FIRST_USER" || die "login names: letters, digits, . _ @ -"
    [[ $POOL =~ ^[0-9.]+/[0-9]+$ ]] || die "--pool must look like 10.10.10.0/24"
    if ip -4 route | awk '{print $1}' | grep -qx "$POOL"; then die "$POOL is already used on this server: pick another with --pool"; fi
    if ! is_ip "$HOST"; then
        local resolved; resolved=$(getent ahostsv4 "$HOST" | awk 'NR==1{print $1}')
        [[ -n $resolved ]] || die "$HOST doesn't resolve yet: point it at $myip (an A record) and run again"
        [[ $resolved == "$myip" ]] || warn "$HOST points at $resolved, but this server is $myip"
    fi

    say "Installing strongSwan"
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    apt-get install -y -qq strongswan-swanctl charon-systemd strongswan-pki libcharon-extra-plugins \
        libstrongswan-extra-plugins iptables openssl curl >/dev/null
    systemctl disable --now strongswan-starter >/dev/null 2>&1 || true
    mkdir -p $SW/{conf.d,x509,x509ca,private}

    if [[ $OWN_CA -eq 0 ]] && ! is_ip "$HOST"; then
        cert_letsencrypt || cert_own_ca
    else
        cert_own_ca
    fi

    write_swanctl
    if [[ ! -s $USERS ]] || ! users_list | grep -q .; then
        [[ -n $FIRST_PW ]] || FIRST_PW=$(random_pw)
        printf '%s\t%s\n' "$FIRST_USER" "$FIRST_PW" | users_write
    fi
    save_conf

    say "Firewall and forwarding"
    write_firewall
    ok "UDP 500 and 4500 open, devices' traffic goes out through $IFACE"

    local svc; svc=$(sw_service)
    systemctl enable "$svc" >/dev/null 2>&1 || true
    systemctl restart "$svc"
    sleep 2
    swanctl --load-all >/dev/null
    swanctl --list-conns 2>/dev/null | grep -q brooog-ikev2 || die "strongSwan didn't load the VPN - see: journalctl -u $svc"
    ok "strongSwan running"

    [[ "$(readlink -f "$0")" == "$SELF" ]] || install -m 700 "$0" "$SELF"
    write_client_files
    show
    echo "${c_warn}If your provider has its own firewall (security group, cloud firewall):${c_0}"
    echo "  open ${c_b}UDP 500${c_0} and ${c_b}UDP 4500${c_0} there too."
    echo "Manage it later with: ${c_b}brooog-ikev2 --add-user NAME${c_0}, --show, --share, --status"
}

case ${1:-} in
    --add-user)  [[ -n ${2:-} ]] || die "usage: $0 --add-user NAME [PASSWORD]"; load_conf; add_user "$2" "${3:-}"; write_client_files ;;
    --del-user)  [[ -n ${2:-} ]] || die "usage: $0 --del-user NAME"; load_conf; del_user "$2"; write_client_files ;;
    --users)     users_list ;;
    --show)      show ;;
    --share)     share ;;
    --status)    status ;;
    --uninstall) uninstall "${2:-}" ;;
    --version)   echo "brooog-ikev2 $VERSION" ;;
    -h|--help)   sed -n '2,35p' "$0" ;;
    *)           install_vpn "$@" ;;
esac
