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

readonly installer_version=1.0.0
readonly installer_label="Mango Bouncer installer $installer_version"
download_base=https://mangoirc.chat/downloads/mango-bouncer
marker='# Managed by the Mango Bouncer installer'

fail() {
    printf 'Mango Bouncer: %s\n' "$*" >&2
    exit 1
}

prompt() {
    local question=$1 default=${2-} answer
    printf '%s' "$question" >&2
    if [[ -n "$default" ]]; then printf ' [%s]' "$default" >&2; fi
    printf ': ' >&2
    IFS= read -r answer || fail 'Input ended before setup was finished.'
    printf '%s' "${answer:-$default}"
}

path_from_input() {
    local value=$1
    if [[ "$value" == \~/* ]]; then value="$HOME/${value:2}"; fi
    [[ -n "$value" && "$value" != *[[:cntrl:]]* && "$value" != *"'"* && "$value" != *\\* ]] ||
        fail 'Enter a path without control characters, apostrophes, or backslashes.'
    realpath -m -- "$value"
}

saved() {
    local key=$1 line
    line=$(grep -m1 "^$key=" "$settings_file") || fail "Missing $key in $settings_file."
    line=${line#*=}
    if [[ "$line" == \'*\' ]]; then line=${line:1:-1}; fi
    printf '%s' "$line"
}

installer_settings() {
    [[ -f "$1" && ! -L "$1" ]] && grep -Fxq "$marker" "$1"
}

private_ipv4() {
    local address=$1
    [[ "$address" =~ ^(10|172|192)\.(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,2})$ ]] || return 1
    local first=${BASH_REMATCH[1]} second=${BASH_REMATCH[2]} third=${BASH_REMATCH[3]} fourth=${BASH_REMATCH[4]}
    (( 10#$second < 256 && 10#$third < 256 && 10#$fourth < 256 )) || return 1
    case "$first" in
        10) return 0 ;;
        172) (( 10#$second >= 16 && 10#$second <= 31 )) ;;
        192) (( 10#$second == 168 )) ;;
    esac
}

compose() {
    MANGO_BOUNCER_VERSION="$version" MANGO_BOUNCER_DATA_TYPE=bind MANGO_BOUNCER_DATA_SOURCE="$data_dir" \
        MANGO_BOUNCER_PUBLISH_ADDRESS="$listen" MANGO_BOUNCER_PORT="$port" \
        docker compose --project-name "$project" --project-directory "$install_dir" \
        --env-file "$env_file" --file "$install_dir/compose.yaml" "$@"
}

case "${1-}" in
    --version)
        printf '%s\n' "$installer_label"
        exit 0
        ;;
    --help|-h)
        printf '%s\n\n' "$installer_label"
        printf 'Usage: bash %s [path-to-mango-bouncer.deb]\n       bash %s --version\n' "${0##*/}" "${0##*/}"
        printf '%s\n' 'Install or update Mango Bouncer with Docker Compose on Linux.' \
            'Download the Mango Bouncer .deb from https://mangoirc.chat/customer/ first.'
        exit 0
        ;;
esac
(( $# <= 1 )) || fail 'Pass one .deb path, or run with --help.'
[[ "$(uname -s)" == Linux ]] || fail 'Run this installer on your Linux Docker host.'
[[ -t 0 ]] || fail 'Open a terminal and run bash install.sh interactively.'
for command in docker curl openssl realpath flock; do
    command -v "$command" >/dev/null || fail "Install $command before running this script."
done
docker compose version >/dev/null || fail 'Install the Docker Compose v2 plugin (docker compose).'
daemon=$(docker info --format '{{.Architecture}} {{.ServerVersion}}') || fail 'Start Docker and make sure your user can run docker info.'
read -r machine engine_version <<< "$daemon"
engine_major=${engine_version%%.*}
if ! [[ "$engine_major" =~ ^[0-9]+$ ]] || (( engine_major < 28 )); then
    fail 'Install Docker Engine 28 or later.'
fi
case "$machine" in
    x86_64|amd64) host_arch=amd64 ;;
    aarch64|arm64) host_arch=arm64 ;;
    *) fail "This Docker host reports $machine. Mango Bouncer requires 64-bit ARM or x86-64." ;;
esac

printf '%s for Linux (%s)\n\n' "$installer_label" "$host_arch"
shopt -s nullglob
candidates=(mango-bouncer_*.deb)
shopt -u nullglob
default_package=
if (( ${#candidates[@]} == 1 )); then default_package=${candidates[0]}; fi
package=${1:-$(prompt 'Path to your downloaded Mango Bouncer .deb' "$default_package")}
package=$(path_from_input "$package")
[[ -f "$package" && -r "$package" ]] || fail "Package is unreadable: $package"
# These substitutions are evaluated by dpkg-deb.
# shellcheck disable=SC2016
format='${Package} ${Version} ${Architecture}\n'
if command -v dpkg-deb >/dev/null; then
    metadata=$(dpkg-deb --show --showformat="$format" "$package") || fail 'Download a fresh copy of the .deb and try again.'
else
    metadata=$(docker run --rm -i --network none ubuntu:26.04 sh -ec '
        cat > /tmp/mango.deb
        dpkg-deb --show --showformat="$1" /tmp/mango.deb
    ' sh "$format" < "$package") || fail 'Could not read the .deb in the Ubuntu container.'
fi
read -r name version architecture extra <<< "$metadata"
[[ "$name" == mango-bouncer && "$version" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?-[0-9]{14}$ && -z "$extra" ]] ||
    fail 'Choose a Mango Bouncer .deb from the Customer area.'
[[ "$architecture" == "$host_arch" ]] || fail "This is the $architecture package. Download the $host_arch package for your Docker host."

install_dir=$(path_from_input "$(prompt 'Installation directory' "$HOME/mango-bouncer")")
[[ "$install_dir" != / ]] || fail 'Choose a dedicated installation directory.'
env_file="$install_dir/.env"
pending_env="$install_dir/.mango-setup.env"
project_files=(.env .mango-setup.env compose.yaml compose.override.yaml compose.override.yml Dockerfile mango-keyring-password packages)
project=$(printf '%s' "$install_dir" | sha256sum | cut -c1-12)
project="mango-bouncer-$project"

mode=new
if installer_settings "$env_file"; then
    mode=installed
    settings_file=$env_file
elif [[ ! -e "$env_file" && ! -L "$env_file" ]] && installer_settings "$pending_env"; then
    mode=resume
    settings_file=$pending_env
fi

if [[ "$mode" != new ]]; then
    data_dir=$(saved MANGO_BOUNCER_DATA_SOURCE)
    listen=$(saved MANGO_BOUNCER_PUBLISH_ADDRESS)
    port=$(saved MANGO_BOUNCER_PORT)
    public_url=$(saved MANGO_BOUNCER_PUBLIC_URL)
    username=$(saved MANGO_BOUNCER_USERNAME)
    [[ -d "$data_dir" ]] || fail 'The saved data directory is missing. Restore it from your backup before continuing.'
    if [[ "$mode" == installed && ( ! -s "$install_dir/mango-keyring-password" || -L "$install_dir/mango-keyring-password" ) ]]; then
        fail 'The saved data directory or keyring password is missing. Restore it from your backup before continuing.'
    fi
else
    data_dir=$(path_from_input "$(prompt 'Data directory for settings, keyring, and chat history' "$install_dir/data")")
    [[ "$data_dir" != / && "$install_dir" != "$data_dir" && "$install_dir" != "$data_dir/"* && "$package" != "$data_dir/"* ]] ||
        fail 'Choose a dedicated data directory separate from the packages and project files.'
    for file in "${project_files[@]}" .mango-install.lock; do
        [[ "$data_dir" != "$install_dir/$file" && "$data_dir" != "$install_dir/$file/"* ]] ||
            fail 'Choose a data directory away from the installer configuration and package paths.'
    done
    while :; do
        port=$(prompt 'Web Access port' 8765)
        [[ "$port" =~ ^[1-9][0-9]{3,4}$ ]] && (( port >= 1024 && port <= 65535 )) && break
        printf 'Enter a port between 1024 and 65535.\n' >&2
    done
    printf '\nHow will you open Web Access?\n  1. This machine or an SSH tunnel\n  2. A private LAN address\n  3. An HTTPS reverse proxy on this machine\n'
    listen=127.0.0.1
    case "$(prompt 'Choose 1, 2, or 3' 1)" in
        1) public_url="http://127.0.0.1:$port" ;;
        2)
            listen=$(prompt 'Private IPv4 address of this Docker host')
            private_ipv4 "$listen" || fail 'Enter a private IPv4 address on this Docker host.'
            public_url="http://$listen:$port"
            ;;
        3)
            public_url=$(prompt 'Public HTTPS URL, such as https://mango.example.com')
            public_url=${public_url%/}
            [[ "$public_url" =~ ^https://[a-zA-Z0-9][a-zA-Z0-9.-]*(:[0-9]{1,5})?$ ]] || fail 'Enter an HTTPS origin without a path.'
            ;;
        *) fail 'Choose 1, 2, or 3.' ;;
    esac
    username=$(prompt 'Web Access username' mango)
    [[ "$username" =~ ^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$ ]] || fail 'Use letters, numbers, dots, underscores or hyphens for the username.'
fi

printf '\nPackage:      %s (%s)\nInstallation: %s\nData:         %s\nKeyring file: %s/mango-keyring-password\nWeb Access:   %s\nHost binding: %s:%s\nUsername:     %s\n\n' \
    "$version" "$architecture" "$install_dir" "$data_dir" "$install_dir" "$public_url" "$listen" "$port" "$username"
case "$(prompt 'Continue with these settings? (y/N)' n)" in
    y|Y|yes|YES) ;;
    *) printf 'Cancelled.\n'; exit 0 ;;
esac

mkdir -p -- "$install_dir"
exec 9>"$install_dir/.mango-install.lock"
flock -n 9 || fail 'An installer is already running for this project.'
if [[ "$mode" == new ]]; then
    for file in "${project_files[@]}"; do
        [[ ! -e "$install_dir/$file" && ! -L "$install_dir/$file" ]] ||
            fail "Found an existing $file in $install_dir. Choose a new installation directory to protect that project."
    done
    mkdir -p -- "$data_dir"
    contents=$(find "$data_dir" -mindepth 1 -maxdepth 1 -print -quit)
    [[ -z "$contents" ]] ||
        fail 'Choose a new or empty data directory.'
elif [[ "$mode" == resume && ( -e "$env_file" || -L "$env_file" ) ]]; then
    fail 'The project was configured by another installer. Run the installer again to use the saved configuration.'
fi

stage=$(mktemp -d "$install_dir/.setup.XXXXXXXX")
trap 'rm -rf -- "$stage"' EXIT

write_environment() {
    printf '%s\nCOMPOSE_PROJECT_NAME=%s\nMANGO_BOUNCER_VERSION=%s\nMANGO_BOUNCER_DATA_TYPE=bind\n' "$marker" "$project" "$version"
    printf "MANGO_BOUNCER_DATA_SOURCE='%s'\nMANGO_BOUNCER_PUBLISH_ADDRESS=%s\nMANGO_BOUNCER_PORT=%s\n" "$data_dir" "$listen" "$port"
    printf "MANGO_BOUNCER_PUBLIC_URL='%s'\nMANGO_BOUNCER_USERNAME=%s\n" "$public_url" "$username"
}

if [[ "$mode" == new ]]; then
    write_environment > "$stage/pending.env"
    mv -- "$stage/pending.env" "$pending_env"
fi
if [[ "$mode" != installed ]]; then
    for file in compose.yaml Dockerfile; do
        if [[ ! -e "$install_dir/$file" ]]; then
            download=$file
            if [[ "$file" == compose.yaml ]]; then download=compose.split.yaml; fi
            curl -fsSL --proto '=https' --retry 2 "$download_base/$download" -o "$stage/$file"
            mv -- "$stage/$file" "$install_dir/$file"
        fi
        [[ -s "$install_dir/$file" && ! -L "$install_dir/$file" ]] || fail "Could not read $install_dir/$file."
    done
    keyring="$install_dir/mango-keyring-password"
    if [[ ! -e "$keyring" && ! -L "$keyring" ]]; then
        openssl rand -hex 32 > "$stage/mango-keyring-password"
        mv -- "$stage/mango-keyring-password" "$keyring"
    fi
    [[ -s "$keyring" && ! -L "$keyring" ]] || fail "Could not read $keyring."
    mv -- "$pending_env" "$env_file"
fi
write_environment > "$stage/.env"
mkdir -p -- "$install_dir/packages"
archive="$install_dir/packages/mango-bouncer_${version}_${architecture}.deb"
if [[ "$package" != "$archive" ]]; then
    cp -- "$package" "$stage/package.deb"
    mv -- "$stage/package.deb" "$archive"
fi

compose config --quiet
compose build mango
# This command runs in the container against the mounted data directory.
# shellcheck disable=SC2016
state=$(compose run --rm --no-deps -T --user 0:0 --cap-add CHOWN --cap-add FOWNER --entrypoint /bin/sh mango -ec '
    for dir in config data cache; do
        target="/var/lib/mango/$dir"
        [ ! -L "$target" ]
        if [ ! -e "$target" ]; then install -d -m 0700 -o 10001 -g 10001 "$target"; fi
    done
    if [ -s /var/lib/mango/config/mango-bouncer/web-access.json ]; then
        printf "configured\n"
    else
        chmod 0700 /var/lib/mango
        chown 10001:10001 /var/lib/mango
        printf "new\n"
    fi
')
case "$state" in
    configured) printf 'Keeping the existing Web Access login and keyring.\n' ;;
    new)
        while :; do
            read -rs -p 'Create a Web Access password: ' password || fail 'Password entry cancelled.'
            printf '\n'
            read -rs -p 'Confirm the Web Access password: ' confirmation || fail 'Password entry cancelled.'
            printf '\n'
            [[ -n "$password" && "$password" == "$confirmation" ]] && break
            printf 'Enter the same nonempty password twice.\n' >&2
        done
        printf '%s\n' "$password" | compose run --rm --no-deps -T mango setup --username "$username" \
            --bind 0.0.0.0 --port "$port" --public-url "$public_url" --password-stdin
        unset password confirmation
        ;;
    *) fail "Unexpected setup status: $state" ;;
esac

mv -- "$stage/.env" "$env_file"
compose up -d --wait --wait-timeout 30
printf '\nOpen %s and sign in as %s, then activate Bouncer with your Mango Account.\n' "$public_url" "$username"
if [[ "$public_url" == https://* ]]; then
    printf 'Point your HTTPS reverse proxy to http://%s:%s.\n' "$listen" "$port"
fi
printf 'Back up %s and %s/mango-keyring-password together.\n' "$data_dir" "$install_dir"
printf 'View logs with: cd %q && docker compose logs -f mango\n' "$install_dir"
