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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
LOCAL_DIR="$ROOT_DIR/local"
STACK_DIR="$LOCAL_DIR/docker-jitsi-meet"
CONFIG_DIR="$LOCAL_DIR/.jitsi-meet-cfg"
RELEASE_FILE="$LOCAL_DIR/.release"

HTTP_PORT="${HTTP_PORT:-8000}"
HTTPS_PORT="${HTTPS_PORT:-8443}"
PUBLIC_URL="${PUBLIC_URL:-https://localhost:${HTTPS_PORT}}"
TZ="${TZ:-Asia/Kolkata}"

set_env() {
    local key="$1"
    local value="$2"
    local file="$STACK_DIR/.env"

    if grep -qE "^#?${key}=" "$file"; then
        perl -0pi -e "s|^#?${key}=.*|${key}=${value}|m" "$file"
    else
        printf '%s=%s\n' "$key" "$value" >> "$file"
    fi
}

mkdir -p "$LOCAL_DIR"

if [[ ! -d "$STACK_DIR" || "${FORCE:-0}" == "1" ]]; then
    rm -rf "$STACK_DIR"

    tmp_dir="$(mktemp -d)"
    trap 'rm -rf "$tmp_dir"' EXIT

    release_json="$(curl -fsSL https://api.github.com/repos/jitsi/docker-jitsi-meet/releases/latest)"
    tag_name="$(printf '%s' "$release_json" | sed -n 's/.*"tag_name": "\([^"]*\)".*/\1/p' | head -1)"
    zip_url="$(printf '%s' "$release_json" | sed -n 's/.*"zipball_url": "\([^"]*\)".*/\1/p' | head -1)"

    if [[ -z "$zip_url" || -z "$tag_name" ]]; then
        echo "Could not detect latest docker-jitsi-meet release from GitHub."
        exit 1
    fi

    curl -LfsS "$zip_url" -o "$tmp_dir/docker-jitsi-meet.zip"
    unzip -q "$tmp_dir/docker-jitsi-meet.zip" -d "$tmp_dir"

    extracted_dir="$(find "$tmp_dir" -maxdepth 1 -type d -name 'jitsi-docker-jitsi-meet-*' | head -1)"
    if [[ -z "$extracted_dir" ]]; then
        echo "Could not find extracted docker-jitsi-meet directory."
        exit 1
    fi

    mv "$extracted_dir" "$STACK_DIR"
    printf '%s\n' "$tag_name" > "$RELEASE_FILE"
fi

created_env=0
if [[ ! -f "$STACK_DIR/.env" ]]; then
    cp "$STACK_DIR/env.example" "$STACK_DIR/.env"
    created_env=1
fi

set_env CONFIG "$CONFIG_DIR"
set_env TZ "$TZ"
set_env HTTP_PORT "$HTTP_PORT"
set_env HTTPS_PORT "$HTTPS_PORT"
set_env PUBLIC_URL "$PUBLIC_URL"

set_env ENABLE_PREJOIN_PAGE 0
set_env ENABLE_WELCOME_PAGE 1
set_env ENABLE_NOISY_MIC_DETECTION 1
set_env ENABLE_NO_AUDIO_DETECTION 1
set_env ENABLE_AV_MODERATION 1
set_env ENABLE_LOBBY 1

set_env START_AUDIO_ONLY 1
set_env START_AUDIO_MUTED 0
set_env START_WITH_AUDIO_MUTED 1
set_env START_VIDEO_MUTED 0
set_env START_WITH_VIDEO_MUTED 1

set_env DISABLE_POLLS 0
set_env DISABLE_DEEP_LINKING 1
set_env DYNAMIC_BRANDING_URL /images/politictalk/branding.json
set_env TOOLBAR_BUTTONS microphone,chat,raisehand,fullscreen,noisesuppression,participants-pane,hangup
set_env HIDE_PREMEETING_BUTTONS microphone,camera,select-background,invite,settings
set_env HIDE_PREJOIN_EXTRA_BUTTONS no-audio,by-phone
set_env XMPP_MUC_MODULES politictalk_roles

set_env ENABLE_AUTH 0
set_env AUTH_TYPE internal
set_env ENABLE_GUESTS 0
set_env JICOFO_ENABLE_AUTH 0
set_env ENABLE_AUTO_OWNER 1
set_env ENABLE_MODERATOR_CHECKS 0
set_env WAIT_FOR_HOST_DISABLE_AUTO_OWNERS false

if [[ "${ENABLE_POLITICTALK_JWT_AUTH:-0}" == "1" ]]; then
    if [[ -z "${POLITICTALK_JITSI_JWT_APP_ID:-}" || -z "${POLITICTALK_JITSI_JWT_APP_SECRET:-}" ]]; then
        echo "Set POLITICTALK_JITSI_JWT_APP_ID and POLITICTALK_JITSI_JWT_APP_SECRET before enabling local JWT auth."
        exit 1
    fi

    set_env ENABLE_AUTH 1
    set_env AUTH_TYPE jwt
    set_env ENABLE_GUESTS 0
    set_env JWT_APP_ID "$POLITICTALK_JITSI_JWT_APP_ID"
    set_env JWT_APP_SECRET "$POLITICTALK_JITSI_JWT_APP_SECRET"
    set_env JWT_ACCEPTED_ISSUERS "$POLITICTALK_JITSI_JWT_APP_ID"
    set_env JWT_ACCEPTED_AUDIENCES "${POLITICTALK_JITSI_JWT_AUDIENCE:-jitsi}"
    set_env JWT_ALLOW_EMPTY 0
    set_env JWT_ENABLE_DOMAIN_VERIFICATION 0
    set_env JICOFO_AUTH_TYPE jwt
    set_env JICOFO_ENABLE_AUTH 1
    set_env ENABLE_AUTO_OWNER 0
    set_env ENABLE_MODERATOR_CHECKS 1
    set_env WAIT_FOR_HOST_DISABLE_AUTO_OWNERS true
fi

mkdir -p "$CONFIG_DIR"/{web,transcripts,prosody/config,prosody/prosody-plugins-custom,jicofo,jvb,jigasi,jibri}

if [[ "$created_env" == "1" || "${REGENERATE_PASSWORDS:-0}" == "1" ]]; then
    (
        cd "$STACK_DIR"
        ./gen-passwords.sh
    )
fi

"$SCRIPT_DIR/local-jitsi-sync.sh"

cat <<EOF
Local Docker Jitsi is prepared.

Next:
  ./scripts/local-jitsi-start.sh

Then open:
  $PUBLIC_URL/pt-local-test
EOF
