#!/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
}

validate_number() {
    local value="$1"
    local field="$2"

    if ! [[ "$value" =~ ^[0-9]+$ ]]; then
        json_error "$field harus berupa angka."
    fi
}

validate_username() {
    local value="$1"

    if [ -z "$value" ]; then
        json_error "Username tidak boleh kosong."
    fi

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

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
}

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
}

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))

account_type="${1:-}"
username="${2:-}"
duration="${3:-}"
quota="${4:-}"
ip_limit="${5:-}"

validasi_input() {
    if ! [[ "$account_type" =~ ^(vmess|vless|trojan|shadowsocks|ssh)$ ]]; then
        json_error "Jenis akun tidak valid. Gunakan vmess, vless, trojan, shadowsocks, atau ssh."
    fi

    validate_username "$username"
    validate_number "$duration" "Masa aktif"

    if [ "$duration" -lt 1 ]; then
        json_error "Masa aktif minimal 1 hari."
    fi

    if [ "$account_type" = "ssh" ]; then
        validate_number "$quota" "Batas IP"
    else
        validate_number "$quota" "Kuota"
        validate_number "$ip_limit" "Batas IP"
    fi

    db_file=$(get_db_file "$account_type")

    if [ ! -f "$db_file" ]; then
        json_error "Database akun $account_type tidak ditemukan."
    fi

    if ! grep -q "^### ${username} " "$db_file"; then
        json_error "Pengguna $username tidak ditemukan pada database $account_type."
    fi
}

perbarui_xray() {
    local protocol="$1"
    local db_file
    local config_file
    local old_exp
    local old_timestamp
    local new_exp
    local credential
    local quota_bytes
    local service_status="berhasil"

    db_file=$(get_db_file "$protocol")
    config_file=$(get_config_file "$protocol")

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

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

    if [ -z "$old_exp" ]; then
        json_error "Tanggal kadaluarsa akun $username tidak ditemukan."
    fi

    old_timestamp=$(date -d "$old_exp" +%s 2>/dev/null)

    if [ -z "$old_timestamp" ]; then
        json_error "Tanggal kadaluarsa akun $username tidak valid."
    fi

    new_exp=$(date -d "$old_exp +${duration} days" +"%Y-%m-%d" 2>/dev/null)

    if [ -z "$new_exp" ]; then
        json_error "Gagal menghitung tanggal kadaluarsa baru."
    fi

    if [ "$quota" != "0" ]; then
        quota_bytes=$((quota * 1024 * 1024 * 1024))
        echo "$quota_bytes" >"/etc/xray/${protocol}/${username}"
    else
        rm -f "/etc/xray/${protocol}/${username}"
    fi

    echo "$ip_limit" >"/etc/xray/${protocol}/${username}IP"

    if [ ! -f "$config_file" ]; then
        json_error "File konfigurasi $protocol tidak ditemukan."
    fi

    sed -i \
        "/^### ${username} /s/^### ${username} [^ ]*/### ${username} ${new_exp}/" \
        "$config_file"

    if [ -n "$credential" ]; then
        sed -i \
            "s|^### ${username} .*|### ${username} ${new_exp} ${credential}|" \
            "$db_file"
    else
        sed -i \
            "s|^### ${username} .*|### ${username} ${new_exp}|" \
            "$db_file"
    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 diperbarui.",\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_lama": "%s",\n' "$(json_escape "$old_exp")"
    printf '    "kadaluarsa_baru": "%s",\n' "$(json_escape "$new_exp")"
    printf '    "penambahan_masa_aktif": "%s hari",\n' "$duration"

    if [ "$quota" = "0" ]; then
        printf '    "quota": "Tanpa Batas",\n'
    else
        printf '    "quota": "%s GB",\n' "$quota"
    fi

    if [ "$ip_limit" = "0" ]; then
        printf '    "ip_limit": "Tanpa Batas",\n'
    else
        printf '    "ip_limit": "%s",\n' "$ip_limit"
    fi

    printf '    "restart_service": "%s"\n' "$service_status"
    printf '  }'

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

    printf '}\n'
}

perbarui_vmess() {
    perbarui_xray "vmess"
}

perbarui_vless() {
    perbarui_xray "vless"
}

perbarui_trojan() {
    perbarui_xray "trojan"
}

perbarui_shadowsocks() {
    perbarui_xray "shadowsocks"
}

perbarui_ssh() {
    local db_file="/etc/ssh/.ssh.db"
    local old_exp
    local old_timestamp
    local new_exp
    local ip_limit_ssh="$quota"
    local service_status="berhasil"

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

    if [ -z "$old_exp" ]; then
        json_error "Tanggal kadaluarsa akun SSH $username tidak ditemukan."
    fi

    old_timestamp=$(date -d "$old_exp" +%s 2>/dev/null)

    if [ -z "$old_timestamp" ]; then
        json_error "Tanggal kadaluarsa akun SSH $username tidak valid."
    fi

    new_exp=$(date -d "$old_exp +${duration} days" +"%Y-%m-%d" 2>/dev/null)

    if [ -z "$new_exp" ]; then
        json_error "Gagal menghitung tanggal kadaluarsa baru akun SSH."
    fi

    if ! id "$username" >/dev/null 2>&1; then
        json_error "Pengguna Linux $username tidak ditemukan."
    fi

    if [ "$ip_limit_ssh" = "0" ]; then
        rm -f "/etc/ssh/${username}"
    else
        echo "$ip_limit_ssh" >"/etc/ssh/${username}"
    fi

    sed -i \
        "s|^### ${username} .*|### ${username} ${new_exp}|" \
        "$db_file"

    if ! chage -E "$new_exp" "$username" >/dev/null 2>&1; then
        json_error "Gagal memperbarui tanggal kadaluarsa pengguna SSH."
    fi

    if ! restart_service "ssh"; then
        service_status="gagal"
    fi

    printf '{\n'
    printf '  "status": "success",\n'
    printf '  "brand": "%s",\n' "$BRAND"
    printf '  "message": "Akun SSH %s berhasil diperbarui.",\n' "$(json_escape "$username")"
    printf '  "data": {\n'
    printf '    "username": "%s",\n' "$(json_escape "$username")"
    printf '    "protocol": "ssh",\n'
    printf '    "kadaluarsa_lama": "%s",\n' "$(json_escape "$old_exp")"
    printf '    "kadaluarsa_baru": "%s",\n' "$(json_escape "$new_exp")"
    printf '    "penambahan_masa_aktif": "%s hari",\n' "$duration"

    if [ "$ip_limit_ssh" = "0" ]; then
        printf '    "ip_limit": "Tanpa Batas",\n'
    else
        printf '    "ip_limit": "%s",\n' "$ip_limit_ssh"
    fi

    printf '    "restart_service": "%s"\n' "$service_status"
    printf '  }'

    if [ "$service_status" = "gagal" ]; then
        printf ',\n'
        printf '  "warning": "Akun SSH berhasil diperbarui, tetapi layanan SSH gagal dimulai ulang."\n'
    else
        printf '\n'
    fi

    printf '}\n'
}

if [ -z "$account_type" ]; then
    printf '{\n'
    printf '  "status": "error",\n'
    printf '  "brand": "%s",\n' "$BRAND"
    printf '  "message": "Jenis akun belum dimasukkan.",\n'
    printf '  "usage": {\n'
    printf '    "vmess": "renew vmess username masa_aktif quota batas_ip",\n'
    printf '    "vless": "renew vless username masa_aktif quota batas_ip",\n'
    printf '    "trojan": "renew trojan username masa_aktif quota batas_ip",\n'
    printf '    "shadowsocks": "renew shadowsocks username masa_aktif quota batas_ip",\n'
    printf '    "ssh": "renew ssh username masa_aktif batas_ip"\n'
    printf '  },\n'
    printf '  "contact": {\n'
    printf '    "WhatsApp": "%s",\n' "$WHATSAPP"
    printf '    "Telegram": "%s"\n' "$TELEGRAM"
    printf '  }\n'
    printf '}\n'

    exit 1
fi

case "$account_type" in
    vmess|vless|trojan|shadowsocks)
        if [ "$#" -lt 5 ]; then
            json_error "Parameter tidak lengkap. Format: $account_type username masa_aktif quota batas_ip"
        fi
        ;;
    ssh)
        if [ "$#" -lt 4 ]; then
            json_error "Parameter tidak lengkap. Format: ssh username masa_aktif batas_ip"
        fi

        quota="${4:-0}"
        ip_limit="$quota"
        ;;
esac

validasi_input

case "$account_type" in
    vmess)
        perbarui_vmess
        ;;
    vless)
        perbarui_vless
        ;;
    trojan)
        perbarui_trojan
        ;;
    shadowsocks)
        perbarui_shadowsocks
        ;;
    ssh)
        perbarui_ssh
        ;;
    *)
        json_error "Jenis akun tidak valid."
        ;;
esac