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

ASTRA_HOST="max@100.106.221.39"
HETZNER_HOST="root@100.120.174.96"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

deploy_target() {
    local name="$1"
    local host target sudo_prefix="" ssh_opts="" scp_opts=""

    case "$name" in
        astra)
            host="$ASTRA_HOST"
            target="aarch64-unknown-linux-gnu"
            sudo_prefix="sudo"
            ;;
        hetzner)
            host="$HETZNER_HOST"
            target="x86_64-unknown-linux-gnu"
            ssh_opts="-p 2200"
            scp_opts="-P 2200"
            ;;
        *)
            echo "Unknown target: $name (use astra, hetzner, or all)"
            exit 1
            ;;
    esac

    echo "=== Building pom for $name ($target) ==="
    cargo zigbuild --release --target "$target" --manifest-path "$PROJECT_DIR/Cargo.toml"

    local binary="$PROJECT_DIR/target/$target/release/pom"

    local config_file="$SCRIPT_DIR/pom-${name}.toml"
    if [ ! -f "$config_file" ]; then
        echo "Config not found: $config_file"
        exit 1
    fi

    echo "=== Deploying to $name ($host) ==="
    ssh $ssh_opts "$host" "$sudo_prefix mkdir -p /etc/pom"
    scp $scp_opts "$binary" "$host:/tmp/pom"
    scp $scp_opts "$config_file" "$host:/tmp/pom.toml"
    scp $scp_opts "$SCRIPT_DIR/pom.service" "$host:/tmp/pom.service"

    ssh $ssh_opts "$host" "$sudo_prefix mv /tmp/pom /usr/local/bin/pom && $sudo_prefix chmod +x /usr/local/bin/pom && $sudo_prefix mv /tmp/pom.toml /etc/pom/pom.toml && $sudo_prefix mv /tmp/pom.service /etc/systemd/system/pom.service"

    # Create env file with Postmark token if it doesn't exist
    ssh $ssh_opts "$host" "if [ ! -f /etc/pom/env ]; then echo 'POM_POSTMARK_TOKEN=SET_ME' | $sudo_prefix tee /etc/pom/env > /dev/null && $sudo_prefix chmod 600 /etc/pom/env; fi"

    ssh $ssh_opts "$host" "$sudo_prefix systemctl daemon-reload && $sudo_prefix systemctl enable pom && $sudo_prefix systemctl restart pom"

    echo "=== $name: deployed ==="
    ssh $ssh_opts "$host" "$sudo_prefix systemctl status pom --no-pager"
}

if [ $# -eq 0 ]; then
    echo "Usage: $0 <astra|hetzner|all>"
    exit 1
fi

case "$1" in
    all)
        deploy_target astra
        deploy_target hetzner
        ;;
    *)
        deploy_target "$1"
        ;;
esac
