#!/usr/bin/env bash
# Script to create/remove a VM in Google Cloud (default city: Taipei / asia-east1-b).
#
# Prerequisites:
# - Bash 4+ (`brew install bash` on macOS)
# - gcloud CLI (`brew install --cask gcloud-cli` on macOS), use `./gcp login`
#
# Example usage:
#   ./gcp login
#   ./gcp projects
#   ./gcp my-project create my-vps
#   ./gcp my-project create my-vps --city taipei --shape e2-micro
#   ./gcp my-project create my-vps --city taipei --cpu 2 --memory 2
#   ./gcp my-project list
#   ./gcp my-project stop my-vps
#   ./gcp my-project start my-vps
#   ./gcp my-project remove my-vps
#   ./gcp logout

set -o errexit
set -o nounset
set -o pipefail
shopt -s extglob

if (( BASH_VERSINFO[0] < 4 )); then
    echo "Bash 4+ is required (macOS: brew install bash)." >&2
    exit 1
fi

declare -A CITY_TO_ZONE=(
    [taipei]="asia-east1-b"
    [hongkong]="asia-east2-a"
    [tokyo]="asia-northeast1-a"
    [singapore]="asia-southeast1-b"
    [zurich]="europe-west6-a"
    [frankfurt]="europe-west3-a"
    [london]="europe-west2-a"
    [losangeles]="us-west2-a"
)

SHAPES=(
    e2-micro
    e2-small
    e2-medium
)

declare -A SHAPE_DESC=(
    [e2-micro]="0.25-2 vCPU, 1GB RAM, ~\$7/mo"
    [e2-small]="0.5-2 vCPU, 2GB RAM, ~\$14/mo"
    [e2-medium]="1-2 vCPU, 4GB RAM, ~\$28/mo"
)

DEFAULT_CITY="taipei"
DEFAULT_SHAPE="e2-micro"  # fine for a proxy server
DEFAULT_CPU="2"
DEFAULT_MEMORY="2"
GITHUB_USER="${USER:-}"
if [[ -z "$GITHUB_USER" || "$GITHUB_USER" == "root" ]]; then
    GITHUB_USER="ymattw"
fi
CITY=""
ZONE=""
SHAPE=""
CPU=""
MEMORY=""
DISK="10"
IMAGE_FAMILY="debian-13"
IMAGE_PROJECT="debian-cloud"
NETWORK="default"
FIREWALL_RULE="vps-ingress"
FIREWALL_TAG="vps-ingress"
FIREWALL_ALLOW="icmp,tcp:22,tcp:80,tcp:443,tcp:60000-65535,udp:60000-65535"
INIT_SCRIPT_URL="https://joyus.org/vps/init"
PROJECT=""

function main
{
    local pos=()

    while [[ $# -gt 0 ]]; do
        case "$1" in
            --shape)
                [[ $# -ge 2 && "$2" != -* ]] || {
                    error "Missing value for --shape. Available shapes:" \
                        "$(available_shapes)"
                    exit 1
                }
                SHAPE="$2"
                shift 2
                ;;
            --cpu)
                [[ $# -ge 2 && "$2" != -* ]] || {
                    error "Missing value for --cpu (vCPU count, e.g. 2)"
                    exit 1
                }
                CPU="$2"
                shift 2
                ;;
            --memory)
                [[ $# -ge 2 && "$2" != -* ]] || {
                    error "Missing value for --memory (memory in GB, e.g. 2)"
                    exit 1
                }
                MEMORY="${2%[gG][bB]}"
                shift 2
                ;;
            --city)
                [[ $# -ge 2 && "$2" != -* ]] || {
                    error "Missing value for --city. Available cities:" \
                        "$(available_cities)"
                    exit 1
                }
                CITY="$2"
                shift 2
                ;;
            --disk)
                [[ $# -ge 2 && "$2" != -* ]] || {
                    error "Missing value for --disk (disk size in GB, e.g. 10)"
                    exit 1
                }
                DISK="${2%[gG][bB]}"
                shift 2
                ;;
            --user)
                [[ $# -ge 2 && "$2" != -* ]] || {
                    error "Missing value for --user (GitHub username)"
                    exit 1
                }
                GITHUB_USER="$2"
                shift 2
                ;;
            --help)
                usage
                exit 0
                ;;
            -*)
                error "Unknown option: $1"
                usage >&2
                exit 1
                ;;
            *)
                pos+=("$1")
                shift
                ;;
        esac
    done

    if [[ ${#pos[@]} -eq 0 ]]; then
        usage
        exit 0
    fi

    check_gcloud

    case "${pos[0]}" in
        login)
            login
            warn_logout
            return 0
            ;;
        logout)
            logout
            return 0
            ;;
        projects)
            list_projects
            warn_logout
            return 0
            ;;
    esac

    PROJECT="${pos[0]}"
    local cmd="${pos[1]:-}"
    local args=("${pos[@]:2}")
    local label=""

    case "$cmd" in
        create)
            label="${args[0]:-}"
            [[ -n "$label" ]] || { error "Missing <label> for 'create'"; usage >&2; exit 1; }
            CITY="${CITY:-$DEFAULT_CITY}"
            resolve_zone
            if [[ -z "$CPU" && -z "$MEMORY" ]]; then
                SHAPE="${SHAPE:-$DEFAULT_SHAPE}"
                resolve_shape
            fi
            validate_label "$label"
            create_vm "$label"
            warn_logout
            ;;
        start)
            label="${args[0]:-}"
            [[ -n "$label" ]] || { error "Missing <label> for 'start'"; usage >&2; exit 1; }
            resolve_vm_zone "$label"
            start_vm "$label"
            warn_logout
            ;;
        stop)
            label="${args[0]:-}"
            [[ -n "$label" ]] || { error "Missing <label> for 'stop'"; usage >&2; exit 1; }
            resolve_vm_zone "$label"
            stop_vm "$label"
            warn_logout
            ;;
        remove)
            label="${args[0]:-}"
            [[ -n "$label" ]] || { error "Missing <label> for 'remove'"; usage >&2; exit 1; }
            resolve_vm_zone "$label"
            remove_vm "$label"
            warn_logout
            ;;
        list)
            if [[ -n "$CITY" ]]; then
                resolve_zone
            fi
            list_vms
            warn_logout
            ;;
        *)
            error "Unknown subcommand: $cmd"
            usage >&2
            exit 1
            ;;
    esac
}

function usage
{
    local prog="$(basename "$0")"
    cat <<EOF
Usage:
  $prog login
  $prog logout
  $prog projects
  $prog <project> create <label> [options]
  $prog <project> start <label> [options]
  $prog <project> stop <label> [options]
  $prog <project> remove <label> [options]
  $prog <project> list [options]

Options:
  --city <city>           City, case-insensitive: $(available_cities) (default: $DEFAULT_CITY)
  --shape <shape>         Machine type: $(available_shapes) (default: $DEFAULT_SHAPE)
  --cpu <count>           Custom vCPU count (overrides --shape; default: $DEFAULT_CPU)
  --memory <GB>           Custom memory in GB (overrides --shape; default: $DEFAULT_MEMORY)
  --disk <GB>             Boot disk size in GB (default: $DISK)
  --user <github_user>    GitHub username for SSH keys (default: $GITHUB_USER)
  --help                  Show this help message

Shapes (est. asia-east1 on-demand):
$(shape_table)
EOF
}

function info
{
    printf '\033[32m%s\033[0m\n' "$*"
}

function warn
{
    printf '\033[33m%s\033[0m\n' "$*" >&2
}

function error
{
    printf '\033[31m%s\033[0m\n' "$*" >&2
}

function warn_logout
{
    warn "Reminder: GCP credentials remain cached on disk (~/.config/gcloud)." \
        "Run '$(basename "$0") logout' when finished."
}

function confirm
{
    local prompt="${1:-Continue?}"
    local reply=""

    read -r -p "$prompt [y/N] " reply
    (shopt -s nocasematch; [[ "$reply" == "y" || "$reply" == "yes" ]])
}

function run_gcloud
{
    gcloud --project="$PROJECT" "$@"
}

function check_gcloud
{
    if ! command -v gcloud >/dev/null 2>&1; then
        error "gcloud CLI is not installed."
        error "  macOS:         brew install --cask gcloud-cli"
        error "  Debian/Ubuntu: sudo apt install google-cloud-cli"
        error "  Other distros: https://cloud.google.com/sdk/docs/install"
        exit 1
    fi
}

function available_cities
{
    printf '%s\n' "${!CITY_TO_ZONE[@]}" \
        | sort \
        | awk 'NR>1{printf ", "} {printf "%s", $0} END{print ""}'
}

function available_shapes
{
    printf '%s\n' "${SHAPES[@]}" \
        | awk 'NR>1{printf ", "} {printf "%s", $0} END{print ""}'
}

function shape_table
{
    local s
    for s in "${SHAPES[@]}"; do
        local suffix=""
        [[ "$s" == "$DEFAULT_SHAPE" ]] && suffix=" (default)"
        printf '  %-11s %s%s\n' "$s" "${SHAPE_DESC[$s]}" "$suffix"
    done
}

function resolve_shape
{
    local normalized="${SHAPE,,}"
    if [[ -z "${SHAPE_DESC[$normalized]:-}" ]]; then
        error "Unknown shape '$SHAPE'. Available shapes: $(available_shapes)"
        exit 1
    fi
    SHAPE="$normalized"
}

function resolve_zone
{
    local normalized="${CITY,,}"
    ZONE="${CITY_TO_ZONE[$normalized]:-}"
    if [[ -z "$ZONE" ]]; then
        error "Unknown city '$CITY'. Available cities: $(available_cities)"
        exit 1
    fi
    CITY="$normalized"
}

function resolve_vm_zone
{
    local label="$1"
    if [[ -n "$CITY" ]]; then
        resolve_zone
        return 0
    fi

    local z
    local zones=()
    while IFS= read -r z; do
        [[ -n "$z" ]] && zones+=("$z")
    done < <(run_gcloud compute instances list \
        --filter="name=($label)" \
        --format='value(zone.basename())')

    if [[ ${#zones[@]} -eq 0 ]]; then
        error "VM '$label' not found in project '$PROJECT'"
        exit 1
    elif [[ ${#zones[@]} -gt 1 ]]; then
        error "Multiple VMs named '$label' found in zones: ${zones[*]}." \
            "Specify --city to disambiguate."
        exit 1
    fi

    ZONE="${zones[0]}"
}

function validate_label
{
    local label="$1"
    if [[ ! "$label" =~ ^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; then
        error "Invalid VM label '$label': must be 1-63 lowercase letters," \
            "digits, or hyphens, starting with a letter and not ending" \
            "with a hyphen."
        exit 1
    fi
}

function ensure_firewall_rule
{
    if run_gcloud compute firewall-rules describe "$FIREWALL_RULE" >/dev/null 2>&1; then
        info "Firewall rule '$FIREWALL_RULE' already exists"
        return 0
    fi

    info "Creating firewall rule '$FIREWALL_RULE' ($FIREWALL_ALLOW)"
    run_gcloud compute firewall-rules create "$FIREWALL_RULE" \
        --direction=INGRESS \
        --priority=1000 \
        --network="$NETWORK" \
        --action=ALLOW \
        --rules="$FIREWALL_ALLOW" \
        --source-ranges=0.0.0.0/0 \
        --target-tags="$FIREWALL_TAG" \
        --description="Allow VPS ingress ($FIREWALL_ALLOW)"
}

function build_ssh_metadata
{
    local out_file="$1"
    local keys_url="https://github.com/${GITHUB_USER}.keys"

    info "Fetching SSH public keys from $keys_url"
    curl -fsSL "$keys_url" \
        | awk -v user="$GITHUB_USER" '{ print user ":" $0 " " user }' \
        > "$out_file"

    if [[ ! -s "$out_file" ]]; then
        error "No SSH keys found at $keys_url"
        exit 1
    fi
}

function build_startup_script
{
    local out_file="$1"
    cat <<EOF > "$out_file"
#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail

MARKER="/var/lib/vps-init.done"
[[ -f "\$MARKER" ]] && exit 0

trap 'echo "VPS_INIT_FAILED"' ERR
export DEBIAN_FRONTEND=noninteractive
command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl)
curl -fsSL "$INIT_SCRIPT_URL" | bash -s "$GITHUB_USER"
touch "\$MARKER"
echo "VPS_INIT_DONE"
EOF
}

function wait_for_init
{
    local label="$1"
    local line tmpdir fifo

    tmpdir="$(mktemp -d)"
    fifo="${tmpdir}/serial.fifo"
    mkfifo "$fifo"

    info "Waiting for init script to finish (Ctrl-C to detach; init continues on VM)..."
    run_gcloud compute instances tail-serial-port-output "$label" --zone="$ZONE" \
        > "$fifo" 2>/dev/null &
    trap "{ kill $!; wait $!; } 2>/dev/null || true; rm -rf $tmpdir" RETURN EXIT

    while IFS= read -r line; do
        # Strip non-color ANSI CSI escapes (e.g. clear screen, cursor move)
        echo "${line//$'\e'\[*([0-9;?])[a-ln-zA-Z]/}"
        if [[ "$line" == *"VPS_INIT_DONE"* ]]; then
            return 0
        elif [[ "$line" == *"VPS_INIT_FAILED"* ]]; then
            return 1
        fi
    done < "$fifo"
}

function create_vm
{
    local label="$1"
    local machine_desc
    local machine_args=()

    if [[ -n "$CPU" || -n "$MEMORY" ]]; then
        if [[ -n "$SHAPE" ]]; then
            warn "Ignoring --shape '$SHAPE' because --cpu/--memory was specified."
        fi
        local cpu="${CPU:-$DEFAULT_CPU}"
        local memory="${MEMORY:-$DEFAULT_MEMORY}"
        machine_desc="custom e2 (${cpu} vCPU, ${memory}GB RAM)"
        machine_args=(
            --custom-vm-type=e2
            --custom-cpu="$cpu"
            --custom-memory="${memory}GB"
        )
    else
        machine_desc="${SHAPE} (${SHAPE_DESC[$SHAPE]})"
        machine_args=(--machine-type="$SHAPE")
    fi

    info "VM configuration:"
    echo "  Project:  $PROJECT"
    echo "  Label:    $label"
    echo "  City:     $CITY ($ZONE)"
    echo "  Machine:  $machine_desc"
    echo "  Disk:     ${DISK}GB (pd-standard)"
    echo "  Image:    ${IMAGE_FAMILY} (${IMAGE_PROJECT})"
    echo "  Network:  ${NETWORK} (firewall: ${FIREWALL_RULE}, ${FIREWALL_ALLOW})"
    echo "  SSH User: ${GITHUB_USER} (https://github.com/${GITHUB_USER}.keys)"
    echo "  Init:     wrapper of ${INIT_SCRIPT_URL} (on first boot)"

    if ! confirm "Create this VM?"; then
        info "Aborted."
        return 0
    fi

    local ssh_metadata_file startup_script_file
    ssh_metadata_file="$(mktemp)"
    startup_script_file="$(mktemp)"
    trap "rm -f $ssh_metadata_file $startup_script_file" EXIT

    ensure_firewall_rule
    build_ssh_metadata "$ssh_metadata_file"
    build_startup_script "$startup_script_file"

    info "Creating VM '$label'..."
    run_gcloud compute instances create "$label" \
        --zone="$ZONE" \
        "${machine_args[@]}" \
        --image-family="$IMAGE_FAMILY" \
        --image-project="$IMAGE_PROJECT" \
        --boot-disk-size="${DISK}GB" \
        --boot-disk-type=pd-standard \
        --network="$NETWORK" \
        --tags="$FIREWALL_TAG" \
        --metadata=enable-oslogin=FALSE \
        --metadata-from-file="ssh-keys=${ssh_metadata_file},startup-script=${startup_script_file}"

    rm -f "$ssh_metadata_file" "$startup_script_file"
    trap - EXIT

    wait_for_init "$label"

    local ip
    ip="$(run_gcloud compute instances describe "$label" \
        --zone="$ZONE" \
        --format='get(networkInterfaces[0].accessConfigs[0].natIP)')"

    info "VM '$label' is ready at $ip"
}

function start_vm
{
    local label="$1"

    info "Starting VM '$label' in $ZONE..."
    run_gcloud compute instances start "$label" --zone="$ZONE"

    local ip
    ip="$(run_gcloud compute instances describe "$label" \
        --zone="$ZONE" \
        --format='get(networkInterfaces[0].accessConfigs[0].natIP)')"

    info "VM '$label' is running at $ip"
}

function stop_vm
{
    local label="$1"

    info "Stopping VM '$label' in $ZONE..."
    run_gcloud compute instances stop "$label" --zone="$ZONE"
    info "VM '$label' stopped."
}

function remove_vm
{
    local label="$1"

    if ! run_gcloud compute instances describe "$label" \
        --zone="$ZONE" \
        --format='table(name,zone.basename())' 2>/dev/null; then
        error "VM '$label' not found in $ZONE (project: $PROJECT)"
        exit 1
    fi

    if ! confirm "Remove VM '$label' in $ZONE?"; then
        info "Aborted."
        return 0
    fi

    info "Removing VM '$label' in $ZONE..."
    run_gcloud compute instances delete "$label" \
        --zone="$ZONE" \
        --quiet
    info "VM '$label' removed."
}

function list_vms
{
    local format="table("
    format+="name,"
    format+="zone.basename(),"
    format+="machineType.basename(),"
    format+="networkInterfaces[0].accessConfigs[0].natIP:label=EXTERNAL_IP,"
    format+="status)"

    local args=(compute instances list --format="$format")
    if [[ -n "$ZONE" ]]; then
        args+=(--filter="zone:($ZONE)")
    fi
    run_gcloud "${args[@]}"
}

function login
{
    gcloud auth login
}

function logout
{
    gcloud auth revoke --all 2>/dev/null || true
    info "Logged out and revoked local gcloud credentials."
}

function list_projects
{
    gcloud projects list --format='table(projectId,name,projectNumber)'
}

main "$@"
