#!/bin/bash

BASE_URL="https://autoscript.interflazz.my.id/v2"
BRAND="INTERFLAZZ.MY.ID"
WHATSAPP="https://wa.me/6285956131443"
TELEGRAM="https://t.me/interflazz"

json_escape() {
    local value="$1"

    value=${value//\\/\\\\}
    value=${value//\"/\\\"}
    value=${value//$'\n'/\\n}
    value=${value//$'\r'/\\r}
    value=${value//$'\t'/\\t}

    printf '%s' "$value"
}

json_error() {
    local message="$1"

    printf '{\n'
    printf '  "status": "error",\n'
    printf '  "brand": "%s",\n' "$(json_escape "$BRAND")"
    printf '  "message": "%s"\n' "$(json_escape "$message")"
    printf '}\n'

    exit 1
}

show_access_denied() {
    local reason="$1"

    printf '{\n'
    printf '  "status": "error",\n'
    printf '  "brand": "%s",\n' "$(json_escape "$BRAND")"
    printf '  "message": "AKSES DITOLAK!",\n'
    printf '  "detail": "%s",\n' "$(json_escape "$reason")"
    printf '  "ip_vps": "%s",\n' "$(json_escape "$vps_ip")"
    printf '  "suggestion": "Silakan beli izin akses script untuk menggunakan layanan ini.",\n'
    printf '  "contact": {\n'
    printf '    "WhatsApp": "%s",\n' "$(json_escape "$WHATSAPP")"
    printf '    "Telegram": "%s"\n' "$(json_escape "$TELEGRAM")"
    printf '  }\n'
    printf '}\n'

    exit 1
}

get_db_file() {
    local protocol="$1"

    case "$protocol" in
        ssh)
            printf '%s' "/etc/ssh/.ssh.db"
            ;;
        vmess|vless|trojan|shadowsocks)
            printf '%s' "/etc/xray/${protocol}/.${protocol}.db"
            ;;
        *)
            return 1
            ;;
    esac
}

get_config_file() {
    local protocol="$1"

    case "$protocol" in
        vmess|vless|trojan|shadowsocks)
            printf '%s' "/etc/xray/${protocol}/config.json"
            ;;
        *)
            return 1
            ;;
    esac
}

validate_protocol() {
    local protocol="$1"

    case "$protocol" in
        vmess|vless|trojan|shadowsocks|ssh)
            return 0
            ;;
        *)
            json_error "Protokol tidak valid. Gunakan vmess, vless, trojan, shadowsocks, atau ssh."
            ;;
    esac
}

validate_username() {
    local username="$1"

    if [ -z "$username" ]; then
        return 1
    fi

    if ! [[ "$username" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        json_error "Username hanya boleh berisi huruf, angka, garis bawah, atau tanda minus."
    fi
}

get_user_list_json() {
    local db_file="$1"
    local first=1
    local username

    printf '['

    if [ -f "$db_file" ]; then
        while IFS= read -r username; do
            [ -z "$username" ] && continue

            if [ "$first" -eq 0 ]; then
                printf ','
            fi

            printf '"%s"' "$(json_escape "$username")"

            first=0
        done < <(
            grep '^### ' "$db_file" 2>/dev/null |
                awk '{print $2}' |
                sort -u
        )
    fi

    printf ']'
}

show_users() {
    local protocol="$1"
    local db_file
    local json_users

    db_file=$(get_db_file "$protocol")

    if [ ! -f "$db_file" ]; then
        printf '{\n'
        printf '  "status": "success",\n'
        printf '  "brand": "%s",\n' "$BRAND"
        printf '  "protocol": "%s",\n' "$(json_escape "$protocol")"
        printf '  "users": [],\n'
        printf '  "message": "Belum ada akun %s yang tersedia."\n' "$(json_escape "$protocol")"
        printf '}\n'
        exit 0
    fi

    json_users=$(get_user_list_json "$db_file")

    printf '{\n'
    printf '  "status": "success",\n'
    printf '  "brand": "%s",\n' "$BRAND"
    printf '  "protocol": "%s",\n' "$(json_escape "$protocol")"
    printf '  "users": %s,\n' "$json_users"
    printf '  "message": "Silakan masukkan username akun %s yang ingin dihapus."\n' "$(json_escape "$protocol")"
    printf '}\n'

    exit 0
}

restart_service() {
    local protocol="$1"

    if [ "$protocol" = "ssh" ]; then
        if systemctl restart ssh >/dev/null 2>&1; then
            return 0
        fi

        if systemctl restart sshd >/dev/null 2>&1; then
            return 0
        fi

        return 1
    fi

    systemctl restart "${protocol}@config" >/dev/null 2>&1
}

delete_xray_config_entries() {
    local protocol="$1"
    local username="$2"
    local config_file="$3"
    local temp_file

    temp_file="${config_file}.delete.${username}.tmp"

    if [ ! -f "$config_file" ]; then
        return 1
    fi

    awk -v user="$username" '
        BEGIN {
            skip = 0
        }

        $0 ~ "^### " user " " {
            skip = 1
            next
        }

        skip == 1 {
            if ($0 ~ /^\},\{"|^\},\{/ || $0 ~ /^\}\,\{/ || $0 ~ /^\},\{/) {
                skip = 0
            }
            next
        }

        {
            print
        }
    ' "$config_file" >"$temp_file"

    if [ -s "$temp_file" ]; then
        mv "$temp_file" "$config_file"
    else
        rm -f "$temp_file"
        return 1
    fi

    return 0
}

delete_user() {
    local protocol="$1"
    local username="$2"
    local db_file
    local config_file=""
    local exp=""
    local service_status="berhasil"
    local user_exists=0

    db_file=$(get_db_file "$protocol")

    if [ ! -f "$db_file" ]; then
        printf '{\n'
        printf '  "status": "error",\n'
        printf '  "brand": "%s",\n' "$BRAND"
        printf '  "message": "Database akun %s tidak ditemukan.",\n' "$(json_escape "$protocol")"
        printf '  "data": {\n'
        printf '    "username": "%s",\n' "$(json_escape "$username")"
        printf '    "protocol": "%s"\n' "$(json_escape "$protocol")"
        printf '  }\n'
        printf '}\n'
        return 1
    fi

    if grep -q "^### ${username} " "$db_file"; then
        user_exists=1
    fi

    if [ "$user_exists" -eq 0 ]; then
        printf '{\n'
        printf '  "status": "error",\n'
        printf '  "brand": "%s",\n' "$BRAND"
        printf '  "message": "Akun %s %s tidak ditemukan.",\n' "$(json_escape "$protocol")" "$(json_escape "$username")"
        printf '  "data": {\n'
        printf '    "username": "%s",\n' "$(json_escape "$username")"
        printf '    "protocol": "%s"\n' "$(json_escape "$protocol")"
        printf '  }\n'
        printf '}\n'
        return 1
    fi

    exp=$(
        grep "^### ${username} " "$db_file" |
            head -1 |
            awk '{print $3}'
    )

    if [ "$protocol" = "ssh" ]; then
        if id "$username" >/dev/null 2>&1; then
            pkill -u "$username" >/dev/null 2>&1
            userdel -f "$username" >/dev/null 2>&1
        fi

        sed -i "/^### ${username} /d" "$db_file"

        rm -f \
            "/etc/ssh/${username}" \
            "/etc/xray/log-createssh-${username}.log" \
            "/var/www/html/ssh-${username}.txt"
    else
        config_file=$(get_config_file "$protocol")

        if [ -f "$config_file" ]; then
            sed -i "/^### ${username} ${exp}$/,+1d" "$config_file"
        fi

        sed -i "/^### ${username} /d" "$db_file"

        rm -f \
            "/etc/xray/${protocol}/${username}" \
            "/etc/xray/${protocol}/${username}IP" \
            "/etc/xray/${protocol}/usage/${username}" \
            "/etc/xray/${protocol}/log-create-${username}.log" \
            "/var/www/html/${protocol}-${username}.txt"

        case "$protocol" in
            vmess|vless)
                rm -f \
                    "/etc/xray/${protocol}/${username}-tls.json" \
                    "/etc/xray/${protocol}/${username}-non.json" \
                    "/etc/xray/${protocol}/${username}-grpc.json"
                ;;
            trojan)
                rm -f \
                    "/etc/xray/trojan/${username}-tls.json" \
                    "/etc/xray/trojan/${username}-non.json" \
                    "/etc/xray/trojan/${username}-grpc.json"
                ;;
        esac
    fi

    if ! restart_service "$protocol"; then
        service_status="gagal"
    fi

    printf '{\n'
    printf '  "status": "success",\n'
    printf '  "brand": "%s",\n' "$BRAND"
    printf '  "message": "Akun %s %s berhasil dihapus.",\n' "$(json_escape "$protocol")" "$(json_escape "$username")"
    printf '  "data": {\n'
    printf '    "username": "%s",\n' "$(json_escape "$username")"
    printf '    "protocol": "%s",\n' "$(json_escape "$protocol")"
    printf '    "kadaluarsa": "%s",\n' "$(json_escape "$exp")"
    printf '    "restart_service": "%s"\n' "$(json_escape "$service_status")"
    printf '  }'

    if [ "$service_status" = "gagal" ]; then
        printf ',\n'
        printf '  "warning": "Akun telah dihapus, tetapi layanan %s gagal dimulai ulang. Silakan periksa status layanan."\n' "$(json_escape "$protocol")"
    else
        printf '\n'
    fi

    printf '}\n'

    return 0
}

vps_ip=$(wget -qO- ipv4.icanhazip.com)

if [ -z "$vps_ip" ]; then
    vps_ip=$(curl -4 -s ipv4.icanhazip.com)
fi

if [ -z "$vps_ip" ]; then
    json_error "Gagal mendapatkan IP publik VPS."
fi

data_acc=$(
    curl -s "${BASE_URL}/access" |
        grep "### $vps_ip " |
        awk '{print $3}'
)

if [ -z "$data_acc" ]; then
    show_access_denied "VPS belum memiliki izin akses script."
fi

expiry_date=$(date -d "$data_acc" +%s 2>/dev/null)
current_date=$(date +%s)

if [ -z "$expiry_date" ]; then
    show_access_denied "Data masa aktif script tidak valid."
fi

if [ "$expiry_date" -le "$current_date" ]; then
    show_access_denied "Masa aktif akses script telah berakhir."
fi

remaining_days=$(((expiry_date - current_date) / 86400))

protocol="${1:-}"
username="${2:-}"

if [ -z "$protocol" ]; then
    printf '{\n'
    printf '  "status": "error",\n'
    printf '  "brand": "%s",\n' "$BRAND"
    printf '  "message": "Protokol belum dimasukkan.",\n'
    printf '  "usage": {\n'
    printf '    "vmess": "hapus vmess username",\n'
    printf '    "vless": "hapus vless username",\n'
    printf '    "trojan": "hapus trojan username",\n'
    printf '    "shadowsocks": "hapus shadowsocks username",\n'
    printf '    "ssh": "hapus ssh username"\n'
    printf '  }\n'
    printf '}\n'

    exit 1
fi

validate_protocol "$protocol"

if [ -z "$username" ]; then
    show_users "$protocol"
fi

validate_username "$username"

delete_user "$protocol" "$username"