install.sh 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. #!/bin/bash
  2. red='\033[0;31m'
  3. green='\033[0;32m'
  4. blue='\033[0;34m'
  5. yellow='\033[0;33m'
  6. plain='\033[0m'
  7. cur_dir=$(pwd)
  8. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  9. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  10. # check root
  11. [[ $EUID -ne 0 ]] && echo -e "${red}Fatal error: ${plain} Please run this script with root privilege \n " && exit 1
  12. # Check OS and set release variable
  13. if [[ -f /etc/os-release ]]; then
  14. source /etc/os-release
  15. release=$ID
  16. elif [[ -f /usr/lib/os-release ]]; then
  17. source /usr/lib/os-release
  18. release=$ID
  19. else
  20. echo "Failed to check the system OS, please contact the author!" >&2
  21. exit 1
  22. fi
  23. echo "The OS release is: $release"
  24. arch() {
  25. case "$(uname -m)" in
  26. x86_64 | x64 | amd64) echo 'amd64' ;;
  27. i*86 | x86) echo '386' ;;
  28. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  29. armv7* | armv7 | arm) echo 'armv7' ;;
  30. armv6* | armv6) echo 'armv6' ;;
  31. armv5* | armv5) echo 'armv5' ;;
  32. s390x) echo 's390x' ;;
  33. *) echo -e "${green}Unsupported CPU architecture! ${plain}" && rm -f install.sh && exit 1 ;;
  34. esac
  35. }
  36. echo "Arch: $(arch)"
  37. # Non-interactive mode: triggered explicitly via XUI_NONINTERACTIVE=1, or
  38. # implicitly when stdin is not a TTY (e.g. `curl ... | bash`, cloud-init).
  39. # In this mode every prompt below is replaced by an env var or a sane default.
  40. if [[ "${XUI_NONINTERACTIVE:-0}" == "1" ]] || [[ ! -t 0 ]]; then
  41. NONINTERACTIVE=1
  42. else
  43. NONINTERACTIVE=0
  44. fi
  45. export NONINTERACTIVE
  46. # Simple helpers
  47. is_ipv4() {
  48. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  49. }
  50. is_ipv6() {
  51. [[ "$1" =~ : ]] && return 0 || return 1
  52. }
  53. is_ip() {
  54. is_ipv4 "$1" || is_ipv6 "$1"
  55. }
  56. is_domain() {
  57. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  58. }
  59. # acme.sh's standalone server binds IPv4 by default; --listen-v6 makes it
  60. # v6-only, which breaks HTTP-01 validation when the domain's A record points
  61. # at this host's IPv4 (#4994). Only force IPv6 when the host has no global
  62. # IPv4 address at all.
  63. acme_listen_flag() {
  64. if ip -4 addr show scope global 2> /dev/null | grep -q "inet "; then
  65. echo ""
  66. else
  67. echo "--listen-v6"
  68. fi
  69. }
  70. # Port helpers
  71. is_port_in_use() {
  72. local port="$1"
  73. if command -v ss > /dev/null 2>&1; then
  74. ss -ltn 2> /dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  75. return
  76. fi
  77. if command -v netstat > /dev/null 2>&1; then
  78. netstat -lnt 2> /dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  79. return
  80. fi
  81. if command -v lsof > /dev/null 2>&1; then
  82. lsof -nP -iTCP:${port} -sTCP:LISTEN > /dev/null 2>&1 && return 0
  83. fi
  84. return 1
  85. }
  86. install_base() {
  87. case "${release}" in
  88. ubuntu | debian | armbian)
  89. apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
  90. ;;
  91. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  92. dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
  93. ;;
  94. centos)
  95. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  96. yum -y update && yum install -y cronie curl tar tzdata socat ca-certificates openssl
  97. else
  98. dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
  99. fi
  100. ;;
  101. arch | manjaro | parch)
  102. pacman -Syu && pacman -Syu --noconfirm cronie curl tar tzdata socat ca-certificates openssl
  103. ;;
  104. opensuse-tumbleweed | opensuse-leap)
  105. zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl
  106. ;;
  107. alpine)
  108. apk update && apk add dcron curl tar tzdata socat ca-certificates openssl
  109. ;;
  110. *)
  111. apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
  112. ;;
  113. esac
  114. }
  115. gen_random_string() {
  116. local length="$1"
  117. openssl rand -base64 $((length * 2)) \
  118. | tr -dc 'a-zA-Z0-9' \
  119. | head -c "$length"
  120. }
  121. # prompt_or_default VARNAME "prompt text" "default" [ENV_NAME]
  122. # Interactive: read into VARNAME. Non-interactive: VARNAME = ${ENV_NAME:-default}.
  123. # ENV_NAME defaults to VARNAME when omitted. Keeps every interactive prompt
  124. # string byte-for-byte identical to the original `read -rp`.
  125. prompt_or_default() {
  126. local __var="$1" __prompt="$2" __default="$3" __env="${4:-$1}"
  127. if [[ "$NONINTERACTIVE" == "1" ]]; then
  128. printf -v "$__var" '%s' "${!__env:-$__default}"
  129. else
  130. # shellcheck disable=SC2229
  131. read -rp "$__prompt" "$__var"
  132. fi
  133. }
  134. # write_install_result <user> <pass> <port> <webpath> <scheme> <host> <token> <dbtype>
  135. # Persists a parseable, root-only credentials file consumed by cloud-init/MOTD.
  136. # Values are written with printf '%q' so a pinned password/username containing
  137. # spaces, quotes, $(...) or backticks is shell-escaped and the file stays safely
  138. # source-able (consumers do '. install-result.env'). For the alphanumeric random
  139. # values gen_random_string emits, %q is a no-op. This is a DIFFERENT file from the
  140. # Postgres env file (/etc/default/x-ui).
  141. write_install_result() {
  142. local u="$1" p="$2" port="$3" wbp="$4" scheme="$5" host="$6" token="$7" dbtype="$8"
  143. local result_file="/etc/x-ui/install-result.env"
  144. local url_host="${host:-SERVER_IP_UNKNOWN}"
  145. install -d -m 755 /etc/x-ui 2> /dev/null
  146. local prev_umask
  147. prev_umask=$(umask)
  148. umask 077
  149. if ! {
  150. printf 'XUI_USERNAME=%q\n' "$u"
  151. printf 'XUI_PASSWORD=%q\n' "$p"
  152. printf 'XUI_PANEL_PORT=%q\n' "$port"
  153. printf 'XUI_WEB_BASE_PATH=%q\n' "$wbp"
  154. printf 'XUI_ACCESS_URL=%q\n' "${scheme}://${url_host}:${port}/${wbp}"
  155. printf 'XUI_API_TOKEN=%q\n' "$token"
  156. printf 'XUI_DB_TYPE=%q\n' "$dbtype"
  157. } > "$result_file"; then
  158. umask "$prev_umask"
  159. echo -e "${yellow}Warning: failed to write ${result_file}.${plain}" >&2
  160. return 1
  161. fi
  162. umask "$prev_umask"
  163. chmod 600 "$result_file" 2> /dev/null
  164. chown root:root "$result_file" 2> /dev/null || true
  165. echo -e "${green}Install result written to ${result_file} (mode 600).${plain}"
  166. }
  167. install_postgres_local() {
  168. local pg_user pg_pass
  169. pg_pass=$(gen_random_string 24)
  170. local pg_db="xui"
  171. local pg_host="127.0.0.1"
  172. local pg_port="5432"
  173. case "${release}" in
  174. ubuntu | debian | armbian)
  175. apt-get update >&2 && apt-get install -y -q postgresql >&2 || return 1
  176. ;;
  177. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  178. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  179. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  180. ;;
  181. centos)
  182. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  183. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  184. else
  185. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  186. fi
  187. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  188. ;;
  189. arch | manjaro | parch)
  190. pacman -Syu --noconfirm postgresql >&2 || return 1
  191. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  192. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  193. fi
  194. ;;
  195. opensuse-tumbleweed | opensuse-leap)
  196. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  197. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  198. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  199. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  200. fi
  201. ;;
  202. alpine)
  203. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  204. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  205. /etc/init.d/postgresql setup >&2 || return 1
  206. fi
  207. rc-update add postgresql default >&2 2> /dev/null || true
  208. rc-service postgresql start >&2 || return 1
  209. ;;
  210. *)
  211. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  212. return 1
  213. ;;
  214. esac
  215. if [[ "${release}" != "alpine" ]]; then
  216. systemctl enable --now postgresql >&2 || return 1
  217. fi
  218. # Wait briefly for the server to accept connections.
  219. local i
  220. for i in 1 2 3 4 5; do
  221. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  222. sleep 1
  223. done
  224. local existing_owner=""
  225. existing_owner=$(sudo -u postgres psql -tAc \
  226. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  227. | tr -d '[:space:]')
  228. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  229. pg_user="${existing_owner}"
  230. else
  231. pg_user=$(gen_random_string 8)
  232. fi
  233. # Idempotent role/db creation. Identifiers are double-quoted because a
  234. # random username may start with a digit, which Postgres rejects unquoted.
  235. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  236. | grep -q 1 \
  237. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  238. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  239. | grep -q 1 \
  240. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  241. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  242. local pg_pass_enc
  243. pg_pass_enc=$(printf '%s' "${pg_pass}" | sed -e 's/%/%25/g' -e 's/:/%3A/g' -e 's/@/%40/g' -e 's|/|%2F|g' -e 's/?/%3F/g' -e 's/#/%23/g')
  244. if [[ -n "${PG_CRED_FILE:-}" ]]; then
  245. local prev_umask
  246. prev_umask=$(umask)
  247. umask 077
  248. if ! cat > "${PG_CRED_FILE}" << EOF; then
  249. PG_USER=${pg_user}
  250. PG_PASS=${pg_pass}
  251. PG_HOST=${pg_host}
  252. PG_PORT=${pg_port}
  253. PG_DB=${pg_db}
  254. EOF
  255. umask "${prev_umask}"
  256. echo -e "${red}Failed to write PostgreSQL credentials to ${PG_CRED_FILE}${plain}" >&2
  257. return 1
  258. fi
  259. umask "${prev_umask}"
  260. fi
  261. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  262. return 0
  263. }
  264. ensure_pg_client() {
  265. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  266. return 0
  267. fi
  268. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore) for in-panel backup...${plain}" >&2
  269. case "${release}" in
  270. ubuntu | debian | armbian)
  271. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  272. ;;
  273. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  274. dnf install -y -q postgresql >&2 || return 1
  275. ;;
  276. centos)
  277. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  278. yum install -y postgresql >&2 || return 1
  279. else
  280. dnf install -y -q postgresql >&2 || return 1
  281. fi
  282. ;;
  283. arch | manjaro | parch)
  284. pacman -Sy --noconfirm postgresql >&2 || return 1
  285. ;;
  286. opensuse-tumbleweed | opensuse-leap)
  287. zypper -q install -y postgresql >&2 || return 1
  288. ;;
  289. alpine)
  290. apk add --no-cache postgresql-client >&2 || return 1
  291. ;;
  292. *)
  293. return 1
  294. ;;
  295. esac
  296. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  297. }
  298. install_acme() {
  299. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  300. cd ~ || return 1
  301. curl -s https://get.acme.sh | sh > /dev/null 2>&1
  302. if [ $? -ne 0 ]; then
  303. echo -e "${red}Failed to install acme.sh${plain}"
  304. return 1
  305. else
  306. echo -e "${green}acme.sh installed successfully${plain}"
  307. fi
  308. return 0
  309. }
  310. setup_ssl_certificate() {
  311. local domain="$1"
  312. local server_ip="$2"
  313. local existing_port="$3"
  314. local existing_webBasePath="$4"
  315. echo -e "${green}Setting up SSL certificate...${plain}"
  316. # Check if acme.sh is installed
  317. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  318. install_acme
  319. if [ $? -ne 0 ]; then
  320. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  321. return 1
  322. fi
  323. fi
  324. # Create certificate directory
  325. local certPath="/root/cert/${domain}"
  326. mkdir -p "$certPath"
  327. # Issue certificate
  328. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  329. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  330. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  331. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport 80 --force
  332. if [ $? -ne 0 ]; then
  333. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  334. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  335. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc 2> /dev/null
  336. rm -rf "$certPath" 2> /dev/null
  337. return 1
  338. fi
  339. # Install certificate
  340. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  341. --key-file /root/cert/${domain}/privkey.pem \
  342. --fullchain-file /root/cert/${domain}/fullchain.pem \
  343. --reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
  344. if [ $? -ne 0 ]; then
  345. echo -e "${yellow}Failed to install certificate${plain}"
  346. return 1
  347. fi
  348. # Enable auto-renew
  349. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  350. # Secure permissions: private key readable only by owner
  351. chmod 600 $certPath/privkey.pem 2> /dev/null
  352. chmod 644 $certPath/fullchain.pem 2> /dev/null
  353. # Set certificate for panel
  354. local webCertFile="/root/cert/${domain}/fullchain.pem"
  355. local webKeyFile="/root/cert/${domain}/privkey.pem"
  356. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  357. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" > /dev/null 2>&1
  358. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  359. return 0
  360. else
  361. echo -e "${yellow}Certificate files not found${plain}"
  362. return 1
  363. fi
  364. }
  365. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  366. # Requires acme.sh and port 80 open for HTTP-01 challenge
  367. setup_ip_certificate() {
  368. local ipv4="$1"
  369. local ipv6="$2" # optional
  370. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  371. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  372. echo -e "${yellow}Default listener is port 80. If you choose another port, ensure external port 80 forwards to it.${plain}"
  373. # Check for acme.sh
  374. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  375. install_acme
  376. if [ $? -ne 0 ]; then
  377. echo -e "${red}Failed to install acme.sh${plain}"
  378. return 1
  379. fi
  380. fi
  381. # Validate IP address
  382. if [[ -z "$ipv4" ]]; then
  383. echo -e "${red}IPv4 address is required${plain}"
  384. return 1
  385. fi
  386. if ! is_ipv4 "$ipv4"; then
  387. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  388. return 1
  389. fi
  390. # Create certificate directory
  391. local certDir="/root/cert/ip"
  392. mkdir -p "$certDir"
  393. # Build domain arguments
  394. local domain_args="-d ${ipv4}"
  395. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  396. domain_args="${domain_args} -d ${ipv6}"
  397. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  398. fi
  399. # Set reload command for auto-renewal (add || true so it doesn't fail during first install)
  400. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  401. # Choose port for HTTP-01 listener (default 80, prompt override)
  402. local WebPort=""
  403. prompt_or_default WebPort "Port to use for ACME HTTP-01 listener (default 80): " "80" XUI_ACME_HTTP_PORT
  404. WebPort="${WebPort:-80}"
  405. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  406. echo -e "${red}Invalid port provided. Falling back to 80.${plain}"
  407. WebPort=80
  408. fi
  409. echo -e "${green}Using port ${WebPort} for standalone validation.${plain}"
  410. if [[ "${WebPort}" -ne 80 ]]; then
  411. echo -e "${yellow}Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${WebPort}.${plain}"
  412. fi
  413. # Ensure chosen port is available
  414. while true; do
  415. if is_port_in_use "${WebPort}"; then
  416. echo -e "${yellow}Port ${WebPort} is in use.${plain}"
  417. local alt_port=""
  418. if [[ "$NONINTERACTIVE" == "1" ]]; then
  419. echo -e "${red}Port ${WebPort} is busy; cannot proceed in non-interactive mode.${plain}"
  420. return 1
  421. fi
  422. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  423. alt_port="${alt_port// /}"
  424. if [[ -z "${alt_port}" ]]; then
  425. echo -e "${red}Port ${WebPort} is busy; cannot proceed.${plain}"
  426. return 1
  427. fi
  428. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  429. echo -e "${red}Invalid port provided.${plain}"
  430. return 1
  431. fi
  432. WebPort="${alt_port}"
  433. continue
  434. else
  435. echo -e "${green}Port ${WebPort} is free and ready for standalone validation.${plain}"
  436. break
  437. fi
  438. done
  439. # Issue certificate with shortlived profile
  440. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  441. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  442. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  443. ~/.acme.sh/acme.sh --issue \
  444. ${domain_args} \
  445. --standalone \
  446. --server letsencrypt \
  447. --certificate-profile shortlived \
  448. --days 6 \
  449. --httpport ${WebPort} \
  450. --force
  451. if [ $? -ne 0 ]; then
  452. echo -e "${red}Failed to issue IP certificate${plain}"
  453. echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}"
  454. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  455. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  456. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  457. rm -rf ${certDir} 2> /dev/null
  458. return 1
  459. fi
  460. echo -e "${green}Certificate issued successfully, installing...${plain}"
  461. # Install certificate
  462. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  463. # but the cert files are still installed. We check for files instead of exit code.
  464. ~/.acme.sh/acme.sh --installcert -d ${ipv4} \
  465. --key-file "${certDir}/privkey.pem" \
  466. --fullchain-file "${certDir}/fullchain.pem" \
  467. --reloadcmd "${reloadCmd}" 2>&1 || true
  468. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  469. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  470. echo -e "${red}Certificate files not found after installation${plain}"
  471. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  472. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  473. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  474. rm -rf ${certDir} 2> /dev/null
  475. return 1
  476. fi
  477. echo -e "${green}Certificate files installed successfully${plain}"
  478. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  479. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  480. # Secure permissions: private key readable only by owner
  481. chmod 600 ${certDir}/privkey.pem 2> /dev/null
  482. chmod 644 ${certDir}/fullchain.pem 2> /dev/null
  483. # Configure panel to use the certificate
  484. echo -e "${green}Setting certificate paths for the panel...${plain}"
  485. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  486. if [ $? -ne 0 ]; then
  487. echo -e "${yellow}Warning: Could not set certificate paths automatically${plain}"
  488. echo -e "${yellow}Certificate files are at:${plain}"
  489. echo -e " Cert: ${certDir}/fullchain.pem"
  490. echo -e " Key: ${certDir}/privkey.pem"
  491. else
  492. echo -e "${green}Certificate paths configured successfully${plain}"
  493. fi
  494. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  495. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  496. echo -e "${yellow}acme.sh will automatically renew and reload x-ui before expiry.${plain}"
  497. return 0
  498. }
  499. # Comprehensive manual SSL certificate issuance via acme.sh
  500. ssl_cert_issue() {
  501. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  502. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  503. # check for acme.sh first
  504. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  505. echo "acme.sh could not be found. Installing now..."
  506. cd ~ || return 1
  507. curl -s https://get.acme.sh | sh
  508. if [ $? -ne 0 ]; then
  509. echo -e "${red}Failed to install acme.sh${plain}"
  510. return 1
  511. else
  512. echo -e "${green}acme.sh installed successfully${plain}"
  513. fi
  514. fi
  515. # get the domain here, and we need to verify it
  516. local domain=""
  517. if [[ "$NONINTERACTIVE" == "1" ]]; then
  518. domain="${XUI_DOMAIN// /}"
  519. if [[ -z "$domain" ]] || ! is_domain "$domain"; then
  520. echo -e "${red}XUI_SSL_MODE=domain requires a valid XUI_DOMAIN (got: '${XUI_DOMAIN:-}').${plain}"
  521. return 1
  522. fi
  523. else
  524. while true; do
  525. read -rp "Please enter your domain name: " domain
  526. domain="${domain// /}" # Trim whitespace
  527. if [[ -z "$domain" ]]; then
  528. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  529. continue
  530. fi
  531. if ! is_domain "$domain"; then
  532. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  533. continue
  534. fi
  535. break
  536. done
  537. fi
  538. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  539. SSL_ISSUED_DOMAIN="${domain}"
  540. # detect existing certificate and reuse it only if its files are actually
  541. # present and non-empty. acme.sh stores ECC certs under ${domain}_ecc and RSA
  542. # certs under ${domain}; a failed issuance can leave a domain entry in --list
  543. # with no usable cert files, which must not be reused (it produces a 0-byte
  544. # fullchain.pem). Broken partial state is cleaned up so issuance can proceed.
  545. local cert_exists=0
  546. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  547. local acmeCertDir=""
  548. if [[ -s ~/.acme.sh/${domain}_ecc/fullchain.cer && -s ~/.acme.sh/${domain}_ecc/${domain}.key ]]; then
  549. acmeCertDir=~/.acme.sh/${domain}_ecc
  550. elif [[ -s ~/.acme.sh/${domain}/fullchain.cer && -s ~/.acme.sh/${domain}/${domain}.key ]]; then
  551. acmeCertDir=~/.acme.sh/${domain}
  552. fi
  553. if [[ -n "${acmeCertDir}" ]]; then
  554. cert_exists=1
  555. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  556. echo -e "${yellow}Existing certificate found for ${domain}, will reuse it.${plain}"
  557. [[ -n "${certInfo}" ]] && echo "$certInfo"
  558. else
  559. echo -e "${yellow}Found incomplete acme.sh state for ${domain} (no valid certificate files); cleaning it up and re-issuing.${plain}"
  560. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  561. fi
  562. fi
  563. if [[ ${cert_exists} -eq 0 ]]; then
  564. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  565. fi
  566. # create a directory for the certificate
  567. certPath="/root/cert/${domain}"
  568. if [ ! -d "$certPath" ]; then
  569. mkdir -p "$certPath"
  570. else
  571. rm -rf "$certPath"
  572. mkdir -p "$certPath"
  573. fi
  574. # get the port number for the standalone server
  575. local WebPort=80
  576. prompt_or_default WebPort "Please choose which port to use (default is 80): " "80" XUI_ACME_HTTP_PORT
  577. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  578. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  579. WebPort=80
  580. fi
  581. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  582. # Stop panel temporarily
  583. echo -e "${yellow}Stopping panel temporarily...${plain}"
  584. systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
  585. if [[ ${cert_exists} -eq 0 ]]; then
  586. # issue the certificate
  587. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  588. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  589. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  590. if [ $? -ne 0 ]; then
  591. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  592. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  593. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  594. return 1
  595. else
  596. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  597. fi
  598. else
  599. echo -e "${green}Using existing certificate, installing certificates...${plain}"
  600. fi
  601. # Setup reload command
  602. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  603. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  604. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  605. if [[ "$NONINTERACTIVE" == "1" ]]; then
  606. setReloadcmd="n"
  607. else
  608. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  609. fi
  610. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  611. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  612. echo -e "${green}\t2.${plain} Input your own command"
  613. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  614. read -rp "Choose an option: " choice
  615. case "$choice" in
  616. 1)
  617. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  618. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  619. ;;
  620. 2)
  621. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  622. read -rp "Please enter your custom reloadcmd: " reloadCmd
  623. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  624. ;;
  625. *)
  626. echo -e "${green}Keeping default reloadcmd${plain}"
  627. ;;
  628. esac
  629. fi
  630. # install the certificate
  631. local installOutput=""
  632. installOutput=$(~/.acme.sh/acme.sh --installcert -d ${domain} \
  633. --key-file /root/cert/${domain}/privkey.pem \
  634. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  635. local installRc=$?
  636. echo "${installOutput}"
  637. local installWroteFiles=0
  638. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  639. installWroteFiles=1
  640. fi
  641. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  642. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  643. else
  644. echo -e "${red}Installing certificate failed, exiting.${plain}"
  645. if [[ ${cert_exists} -eq 0 ]]; then
  646. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  647. fi
  648. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  649. return 1
  650. fi
  651. # enable auto-renew
  652. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  653. if [ $? -ne 0 ]; then
  654. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  655. ls -lah /root/cert/${domain}/
  656. # Secure permissions: private key readable only by owner
  657. chmod 600 $certPath/privkey.pem 2> /dev/null
  658. chmod 644 $certPath/fullchain.pem 2> /dev/null
  659. else
  660. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  661. ls -lah /root/cert/${domain}/
  662. # Secure permissions: private key readable only by owner
  663. chmod 600 $certPath/privkey.pem 2> /dev/null
  664. chmod 644 $certPath/fullchain.pem 2> /dev/null
  665. fi
  666. # start panel
  667. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  668. # Prompt user to set panel paths after successful certificate installation
  669. if [[ "$NONINTERACTIVE" == "1" ]]; then
  670. setPanel="y"
  671. else
  672. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  673. fi
  674. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  675. local webCertFile="/root/cert/${domain}/fullchain.pem"
  676. local webKeyFile="/root/cert/${domain}/privkey.pem"
  677. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  678. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  679. echo -e "${green}Certificate paths set for the panel${plain}"
  680. echo -e "${green}Certificate File: $webCertFile${plain}"
  681. echo -e "${green}Private Key File: $webKeyFile${plain}"
  682. echo ""
  683. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  684. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  685. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  686. else
  687. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  688. fi
  689. else
  690. echo -e "${yellow}Skipping panel path setting.${plain}"
  691. fi
  692. return 0
  693. }
  694. # Reusable interactive SSL setup (domain or IP)
  695. # Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
  696. prompt_and_setup_ssl() {
  697. local panel_port="$1"
  698. local web_base_path="$2"
  699. local server_ip="$3"
  700. local ssl_choice=""
  701. SSL_SCHEME="https"
  702. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  703. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  704. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  705. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  706. echo -e "${green}4.${plain} Skip SSL (advanced — behind reverse proxy / SSH tunnel only)"
  707. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  708. echo -e "${blue}Note:${plain} Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel."
  709. if [[ "$NONINTERACTIVE" == "1" ]]; then
  710. case "${XUI_SSL_MODE:-none}" in
  711. domain) ssl_choice="1" ;;
  712. ip) ssl_choice="2" ;;
  713. none | "") ssl_choice="4" ;;
  714. *)
  715. echo -e "${yellow}Unknown XUI_SSL_MODE='${XUI_SSL_MODE}', defaulting to none (HTTP).${plain}"
  716. ssl_choice="4"
  717. ;;
  718. esac
  719. else
  720. read -rp "Choose an option (default 2 for IP): " ssl_choice
  721. ssl_choice="${ssl_choice// /}" # Trim whitespace
  722. # Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
  723. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" && "$ssl_choice" != "4" ]]; then
  724. ssl_choice="2"
  725. fi
  726. fi
  727. case "$ssl_choice" in
  728. 1)
  729. # User chose Let's Encrypt domain option
  730. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  731. if ssl_cert_issue; then
  732. local cert_domain="${SSL_ISSUED_DOMAIN}"
  733. if [[ -z "${cert_domain}" ]]; then
  734. cert_domain=$(~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}')
  735. fi
  736. if [[ -n "${cert_domain}" ]]; then
  737. SSL_HOST="${cert_domain}"
  738. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  739. else
  740. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  741. SSL_HOST="${server_ip}"
  742. fi
  743. else
  744. echo -e "${red}SSL certificate setup failed for domain mode.${plain}"
  745. SSL_HOST="${server_ip}"
  746. fi
  747. ;;
  748. 2)
  749. # User chose Let's Encrypt IP certificate option
  750. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  751. # Ask for optional IPv6
  752. local ipv6_addr=""
  753. prompt_or_default ipv6_addr "Do you have an IPv6 address to include? (leave empty to skip): " "" XUI_SSL_IPV6
  754. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  755. # Stop panel if running (port 80 needed)
  756. if [[ $release == "alpine" ]]; then
  757. rc-service x-ui stop > /dev/null 2>&1
  758. else
  759. systemctl stop x-ui > /dev/null 2>&1
  760. fi
  761. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  762. if [ $? -eq 0 ]; then
  763. SSL_HOST="${server_ip}"
  764. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  765. else
  766. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  767. SSL_HOST="${server_ip}"
  768. fi
  769. ;;
  770. 3)
  771. # User chose Custom Paths (User Provided) option
  772. echo -e "${green}Using custom existing certificate...${plain}"
  773. local custom_cert=""
  774. local custom_key=""
  775. local custom_domain=""
  776. # 3.1 Request Domain to compose Panel URL later
  777. read -rp "Please enter domain name certificate issued for: " custom_domain
  778. custom_domain="${custom_domain// /}" # Remove spaces
  779. # 3.2 Loop for Certificate Path
  780. while true; do
  781. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  782. # Strip quotes if present
  783. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  784. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  785. break
  786. elif [[ ! -f "$custom_cert" ]]; then
  787. echo -e "${red}Error: File does not exist! Try again.${plain}"
  788. elif [[ ! -r "$custom_cert" ]]; then
  789. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  790. else
  791. echo -e "${red}Error: File is empty!${plain}"
  792. fi
  793. done
  794. # 3.3 Loop for Private Key Path
  795. while true; do
  796. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  797. # Strip quotes if present
  798. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  799. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  800. break
  801. elif [[ ! -f "$custom_key" ]]; then
  802. echo -e "${red}Error: File does not exist! Try again.${plain}"
  803. elif [[ ! -r "$custom_key" ]]; then
  804. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  805. else
  806. echo -e "${red}Error: File is empty!${plain}"
  807. fi
  808. done
  809. # 3.4 Apply Settings via x-ui binary
  810. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" > /dev/null 2>&1
  811. # Set SSL_HOST for composing Panel URL
  812. if [[ -n "$custom_domain" ]]; then
  813. SSL_HOST="$custom_domain"
  814. else
  815. SSL_HOST="${server_ip}"
  816. fi
  817. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  818. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  819. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  820. ;;
  821. 4)
  822. echo ""
  823. echo -e "${red}⚠ Panel will be installed WITHOUT SSL/TLS.${plain}"
  824. echo -e "${yellow}Login credentials and cookies will travel as plain HTTP.${plain}"
  825. echo -e "${yellow}Only safe when:${plain}"
  826. echo -e "${yellow} • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or${plain}"
  827. echo -e "${yellow} • You access the panel exclusively via SSH tunnel${plain}"
  828. echo ""
  829. SSL_SCHEME="http"
  830. SSL_HOST="${server_ip}"
  831. local bind_local=""
  832. if [[ "$NONINTERACTIVE" == "1" ]]; then
  833. # Cloud images must stay reachable on their public interface.
  834. bind_local="n"
  835. else
  836. read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
  837. fi
  838. if [[ "$bind_local" == "y" || "$bind_local" == "Y" ]]; then
  839. ${xui_folder}/x-ui setting -listenIP "127.0.0.1" > /dev/null 2>&1
  840. SSL_HOST="127.0.0.1"
  841. echo -e "${green}✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet.${plain}"
  842. echo ""
  843. echo -e "${green}SSH Port Forwarding — open the panel from your local machine via:${plain}"
  844. echo -e " Standard SSH command:"
  845. echo -e " ${yellow}ssh -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  846. echo -e " If using an SSH key:"
  847. echo -e " ${yellow}ssh -i <sshkeypath> -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  848. echo -e " Then open in your browser:"
  849. echo -e " ${yellow}http://localhost:2222/${web_base_path}${plain}"
  850. echo ""
  851. echo -e "${yellow}Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1:${panel_port} and let it terminate TLS.${plain}"
  852. else
  853. echo -e "${yellow}Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it.${plain}"
  854. fi
  855. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  856. echo -e "${green}✓ SSL setup skipped.${plain}"
  857. ;;
  858. *)
  859. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  860. SSL_HOST="${server_ip}"
  861. ;;
  862. esac
  863. }
  864. config_after_install() {
  865. local existing_hasDefaultCredential=$(${xui_folder}/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
  866. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  867. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  868. # Properly detect empty cert by checking if cert: line exists and has content after it
  869. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  870. local URL_lists=(
  871. "https://api4.ipify.org"
  872. "https://ipv4.icanhazip.com"
  873. "https://v4.api.ipinfo.io/ip"
  874. "https://ipv4.myexternalip.com/raw"
  875. "https://4.ident.me"
  876. "https://check-host.net/ip"
  877. )
  878. local server_ip=""
  879. for ip_address in "${URL_lists[@]}"; do
  880. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  881. local http_code=$(echo "$response" | tail -n1)
  882. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  883. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  884. server_ip="${ip_result}"
  885. break
  886. fi
  887. done
  888. if [[ -z "$server_ip" ]]; then
  889. if [[ "$NONINTERACTIVE" == "1" ]]; then
  890. # Panel binds 0.0.0.0 regardless; the IP is only used to compose the
  891. # displayed access URL. Fall back to XUI_SERVER_IP or leave blank.
  892. server_ip="${XUI_SERVER_IP:-}"
  893. else
  894. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  895. while [[ -z "$server_ip" ]]; do
  896. read -rp "Please enter your server's public IPv4 address: " server_ip
  897. server_ip="${server_ip// /}"
  898. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  899. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  900. server_ip=""
  901. fi
  902. done
  903. fi
  904. fi
  905. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  906. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  907. local config_webBasePath="${XUI_WEB_BASE_PATH:-$(gen_random_string 18)}"
  908. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  909. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  910. local config_port=""
  911. local db_label="SQLite (/etc/x-ui/x-ui.db)"
  912. echo ""
  913. echo -e "${green}═══════════════════════════════════════════${plain}"
  914. echo -e "${green} Database Selection ${plain}"
  915. echo -e "${green}═══════════════════════════════════════════${plain}"
  916. echo -e " 1) SQLite (default — recommended for < 500 clients)"
  917. echo -e " 2) PostgreSQL (recommended for high client counts / many nodes)"
  918. if [[ "$NONINTERACTIVE" == "1" ]]; then
  919. if [[ "${XUI_DB_TYPE:-sqlite}" == "postgres" ]]; then
  920. db_choice="2"
  921. else
  922. db_choice="1"
  923. fi
  924. else
  925. read -rp "Choose [1]: " db_choice
  926. db_choice="${db_choice:-1}"
  927. fi
  928. if [[ "$db_choice" == "2" ]]; then
  929. local xui_env_file
  930. case "${release}" in
  931. ubuntu | debian | armbian)
  932. xui_env_file="/etc/default/x-ui"
  933. ;;
  934. arch | manjaro | parch | alpine)
  935. xui_env_file="/etc/conf.d/x-ui"
  936. ;;
  937. *)
  938. xui_env_file="/etc/sysconfig/x-ui"
  939. ;;
  940. esac
  941. local xui_dsn=""
  942. local pg_mode=""
  943. local pg_local_installed=0
  944. while [[ -z "$xui_dsn" ]]; do
  945. if [[ "$NONINTERACTIVE" == "1" ]]; then
  946. if [[ -n "${XUI_DB_DSN:-}" ]]; then
  947. xui_dsn="${XUI_DB_DSN}"
  948. db_label="PostgreSQL (external)"
  949. break
  950. fi
  951. echo -e "${yellow}Installing PostgreSQL locally (non-interactive)...${plain}"
  952. local pg_cred_file
  953. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  954. if [[ -n "${pg_cred_file}" ]] && xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  955. pg_local_installed=1
  956. if [[ -r "${pg_cred_file}" ]]; then
  957. # shellcheck disable=SC1090
  958. source "${pg_cred_file}"
  959. fi
  960. rm -f "${pg_cred_file}"
  961. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  962. break
  963. fi
  964. rm -f "${pg_cred_file}"
  965. echo -e "${red}PostgreSQL installation failed in non-interactive mode; aborting.${plain}"
  966. echo -e "${yellow}Set XUI_DB_DSN to use an existing server, or XUI_DB_TYPE=sqlite.${plain}"
  967. exit 1
  968. fi
  969. echo ""
  970. echo -e " 1) Install PostgreSQL locally and create a dedicated user/db (recommended)"
  971. echo -e " 2) Use an existing PostgreSQL server (enter DSN)"
  972. read -rp "Choose [1]: " pg_mode
  973. pg_mode="${pg_mode:-1}"
  974. if [[ "$pg_mode" == "2" ]]; then
  975. while [[ -z "$xui_dsn" ]]; do
  976. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " xui_dsn
  977. xui_dsn="${xui_dsn// /}"
  978. done
  979. db_label="PostgreSQL (external)"
  980. else
  981. echo -e "${yellow}Installing PostgreSQL — this may take a moment...${plain}"
  982. local pg_cred_file
  983. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  984. if [[ -z "${pg_cred_file}" ]]; then
  985. echo -e "${red}Failed to create temporary credentials file.${plain}"
  986. xui_dsn=""
  987. continue
  988. fi
  989. if xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  990. pg_local_installed=1
  991. if [[ -r "${pg_cred_file}" ]]; then
  992. # shellcheck disable=SC1090
  993. source "${pg_cred_file}"
  994. fi
  995. rm -f "${pg_cred_file}"
  996. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  997. else
  998. rm -f "${pg_cred_file}"
  999. echo ""
  1000. echo -e "${red}PostgreSQL installation failed.${plain}"
  1001. echo -e " 1) Retry local install"
  1002. echo -e " 2) Enter an external DSN instead"
  1003. echo -e " 3) Abort install"
  1004. echo -e " 4) Fall back to SQLite"
  1005. read -rp "Choose [1]: " pg_fail
  1006. pg_fail="${pg_fail:-1}"
  1007. case "$pg_fail" in
  1008. 2) pg_mode="2" ;;
  1009. 3)
  1010. echo -e "${red}Install aborted.${plain}"
  1011. exit 1
  1012. ;;
  1013. 4)
  1014. db_choice="1"
  1015. xui_dsn=""
  1016. break
  1017. ;;
  1018. *) xui_dsn="" ;;
  1019. esac
  1020. fi
  1021. fi
  1022. done
  1023. if [[ -n "$xui_dsn" ]]; then
  1024. install -d -m 755 "$(dirname "$xui_env_file")"
  1025. umask 077
  1026. cat > "$xui_env_file" << EOF
  1027. XUI_DB_TYPE=postgres
  1028. XUI_DB_DSN=${xui_dsn}
  1029. EOF
  1030. chmod 600 "$xui_env_file"
  1031. umask 022
  1032. export XUI_DB_TYPE=postgres
  1033. export XUI_DB_DSN="${xui_dsn}"
  1034. ensure_pg_client || echo -e "${yellow}⚠ Could not install pg_dump/pg_restore. In-panel database backup/restore will be unavailable until you install the postgresql-client package.${plain}"
  1035. fi
  1036. fi
  1037. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1038. if [[ -n "${XUI_PANEL_PORT:-}" ]]; then
  1039. config_port="${XUI_PANEL_PORT}"
  1040. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1041. else
  1042. config_port=$(shuf -i 1024-62000 -n 1)
  1043. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1044. fi
  1045. else
  1046. read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
  1047. if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
  1048. read -rp "Please set up the panel port: " config_port
  1049. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1050. else
  1051. config_port=$(shuf -i 1024-62000 -n 1)
  1052. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1053. fi
  1054. fi
  1055. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
  1056. echo ""
  1057. echo -e "${green}═══════════════════════════════════════════${plain}"
  1058. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1059. echo -e "${green}═══════════════════════════════════════════${plain}"
  1060. echo -e "${yellow}SSL is strongly recommended. Skip only if a reverse proxy${plain}"
  1061. echo -e "${yellow}or SSH tunnel handles TLS for you.${plain}"
  1062. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1063. echo ""
  1064. prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}"
  1065. # Retrieve the API token for display
  1066. local config_apiToken=$(${xui_folder}/x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1067. # Display final credentials and access information
  1068. echo ""
  1069. echo -e "${green}═══════════════════════════════════════════${plain}"
  1070. echo -e "${green} Panel Installation Complete! ${plain}"
  1071. echo -e "${green}═══════════════════════════════════════════${plain}"
  1072. echo -e "${green}Username: ${config_username}${plain}"
  1073. echo -e "${green}Password: ${config_password}${plain}"
  1074. echo -e "${green}Port: ${config_port}${plain}"
  1075. echo -e "${green}WebBasePath: ${config_webBasePath}${plain}"
  1076. echo -e "${green}Database: ${db_label}${plain}"
  1077. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain}"
  1078. echo -e "${green}API Token: ${config_apiToken}${plain}"
  1079. echo -e "${green}═══════════════════════════════════════════${plain}"
  1080. echo -e "${yellow}⚠ IMPORTANT: Save these credentials securely!${plain}"
  1081. if [[ "$SSL_SCHEME" == "https" ]]; then
  1082. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  1083. else
  1084. echo -e "${yellow}⚠ SSL Certificate: Skipped — panel is HTTP-only. Use a reverse proxy or SSH tunnel.${plain}"
  1085. fi
  1086. if [[ "$db_choice" == "2" ]]; then
  1087. echo ""
  1088. echo -e "${green}PostgreSQL backup & restore is built into the panel:${plain}"
  1089. echo -e " ${blue}${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain} → Backup & Restore"
  1090. echo -e "${yellow} Back Up downloads a pg_dump .dump file; Restore reloads it via pg_restore.${plain}"
  1091. fi
  1092. if [[ "$db_choice" == "2" && "$pg_local_installed" == "1" ]]; then
  1093. echo ""
  1094. echo -e "${green}═══════════════════════════════════════════${plain}"
  1095. echo -e "${green} PostgreSQL Credentials ${plain}"
  1096. echo -e "${green}═══════════════════════════════════════════${plain}"
  1097. echo -e "${green}DB Name: ${PG_DB}${plain}"
  1098. echo -e "${green}Username: ${PG_USER}${plain}"
  1099. echo -e "${green}Password: ${PG_PASS}${plain}"
  1100. echo -e "${green}Host: ${PG_HOST}${plain}"
  1101. echo -e "${green}Port: ${PG_PORT}${plain}"
  1102. echo -e "${green}DSN: ${xui_dsn}${plain}"
  1103. echo -e "${green}Env file: ${xui_env_file}${plain}"
  1104. echo -e "${green}-------------------------------------------${plain}"
  1105. echo -e "${green}Connect from this server:${plain}"
  1106. echo -e " ${blue}sudo -u postgres psql -d ${PG_DB}${plain} (as the postgres superuser)"
  1107. echo -e " ${blue}PGPASSWORD='${PG_PASS}' psql -h ${PG_HOST} -p ${PG_PORT} -U ${PG_USER} -d ${PG_DB}${plain}"
  1108. echo -e "${green}═══════════════════════════════════════════${plain}"
  1109. echo -e "${yellow}⚠ The panel reads these credentials from ${xui_env_file}.${plain}"
  1110. echo -e "${yellow}⚠ Save the password — it is not stored anywhere else in plain text.${plain}"
  1111. unset PG_USER PG_PASS PG_HOST PG_PORT PG_DB
  1112. fi
  1113. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1114. : "${SSL_SCHEME:=https}"
  1115. : "${SSL_HOST:=${server_ip}}"
  1116. local db_type_out="sqlite"
  1117. [[ "$db_choice" == "2" ]] && db_type_out="postgres"
  1118. write_install_result "${config_username}" "${config_password}" "${config_port}" \
  1119. "${config_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${db_type_out}"
  1120. else
  1121. local config_webBasePath=$(gen_random_string 18)
  1122. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  1123. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  1124. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  1125. # If the panel is already installed but no certificate is configured, prompt for SSL now
  1126. if [[ -z "${existing_cert}" ]]; then
  1127. echo ""
  1128. echo -e "${green}═══════════════════════════════════════════${plain}"
  1129. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1130. echo -e "${green}═══════════════════════════════════════════${plain}"
  1131. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1132. echo ""
  1133. prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}"
  1134. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}"
  1135. else
  1136. # If a cert already exists, just show the access URL
  1137. echo -e "${green}Access URL: https://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
  1138. fi
  1139. fi
  1140. else
  1141. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  1142. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  1143. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  1144. echo -e "${yellow}Default credentials detected. Security update required...${plain}"
  1145. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}"
  1146. echo -e "Generated new random login credentials:"
  1147. echo -e "###############################################"
  1148. echo -e "${green}Username: ${config_username}${plain}"
  1149. echo -e "${green}Password: ${config_password}${plain}"
  1150. echo -e "###############################################"
  1151. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1152. local config_apiToken
  1153. config_apiToken=$(${xui_folder}/x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1154. : "${SSL_SCHEME:=https}"
  1155. : "${SSL_HOST:=${server_ip}}"
  1156. write_install_result "${config_username}" "${config_password}" "${existing_port}" \
  1157. "${existing_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${XUI_DB_TYPE:-sqlite}"
  1158. else
  1159. echo -e "${green}Username, Password, and WebBasePath are properly set.${plain}"
  1160. fi
  1161. # Existing install: if no cert configured, prompt user for SSL setup
  1162. # Properly detect empty cert by checking if cert: line exists and has content after it
  1163. existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1164. if [[ -z "$existing_cert" ]]; then
  1165. echo ""
  1166. echo -e "${green}═══════════════════════════════════════════${plain}"
  1167. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1168. echo -e "${green}═══════════════════════════════════════════${plain}"
  1169. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1170. echo ""
  1171. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  1172. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  1173. else
  1174. echo -e "${green}SSL certificate already configured. No action needed.${plain}"
  1175. fi
  1176. fi
  1177. ${xui_folder}/x-ui migrate
  1178. }
  1179. install_x-ui() {
  1180. cd ${xui_folder%/x-ui}/
  1181. # Download resources
  1182. if [ $# == 0 ]; then
  1183. tag_version=$(curl -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  1184. if [[ ! -n "$tag_version" ]]; then
  1185. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  1186. tag_version=$(curl -4 -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  1187. if [[ ! -n "$tag_version" ]]; then
  1188. echo -e "${red}Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later${plain}"
  1189. exit 1
  1190. fi
  1191. fi
  1192. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  1193. curl -4fLRo ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz
  1194. if [[ $? -ne 0 ]]; then
  1195. echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
  1196. exit 1
  1197. fi
  1198. else
  1199. tag_version=$1
  1200. tag_version_numeric=${tag_version#v}
  1201. min_version="2.3.5"
  1202. if [[ "$(printf '%s\n' "$min_version" "$tag_version_numeric" | sort -V | head -n1)" != "$min_version" ]]; then
  1203. echo -e "${red}Please use a newer version (at least v2.3.5). Exiting installation.${plain}"
  1204. exit 1
  1205. fi
  1206. url="https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz"
  1207. echo -e "Beginning to install x-ui $1"
  1208. curl -4fLRo ${xui_folder}-linux-$(arch).tar.gz ${url}
  1209. if [[ $? -ne 0 ]]; then
  1210. echo -e "${red}Download x-ui $1 failed, please check if the version exists ${plain}"
  1211. exit 1
  1212. fi
  1213. fi
  1214. curl -4fLRo /usr/bin/x-ui-temp https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
  1215. if [[ $? -ne 0 ]]; then
  1216. echo -e "${red}Failed to download x-ui.sh${plain}"
  1217. exit 1
  1218. fi
  1219. # Stop x-ui service and remove old resources
  1220. if [[ -e ${xui_folder}/ ]]; then
  1221. if [[ $release == "alpine" ]]; then
  1222. rc-service x-ui stop
  1223. else
  1224. systemctl stop x-ui
  1225. fi
  1226. # Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
  1227. # lifecycle, so on Linux a stale one can survive the stop and keep holding
  1228. # an inbound port with an outdated secret, silently breaking new clients.
  1229. # The freshly installed panel respawns a clean mtg per inbound on start.
  1230. pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
  1231. rm ${xui_folder}/ -rf
  1232. fi
  1233. # Extract resources and set permissions
  1234. tar zxvf x-ui-linux-$(arch).tar.gz
  1235. rm x-ui-linux-$(arch).tar.gz -f
  1236. cd x-ui
  1237. chmod +x x-ui
  1238. chmod +x x-ui.sh
  1239. # Check the system's architecture and rename the file accordingly
  1240. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  1241. mv bin/xray-linux-$(arch) bin/xray-linux-arm
  1242. chmod +x bin/xray-linux-arm
  1243. if [[ -f bin/mtg-linux-$(arch) ]]; then
  1244. mv bin/mtg-linux-$(arch) bin/mtg-linux-arm
  1245. chmod +x bin/mtg-linux-arm
  1246. fi
  1247. fi
  1248. chmod +x x-ui bin/xray-linux-$(arch)
  1249. if [[ -f bin/mtg-linux-arm ]]; then
  1250. chmod +x bin/mtg-linux-arm
  1251. elif [[ -f bin/mtg-linux-$(arch) ]]; then
  1252. chmod +x bin/mtg-linux-$(arch)
  1253. fi
  1254. # Update x-ui cli and se set permission
  1255. mv -f /usr/bin/x-ui-temp /usr/bin/x-ui
  1256. chmod +x /usr/bin/x-ui
  1257. mkdir -p /var/log/x-ui
  1258. config_after_install
  1259. # Etckeeper compatibility
  1260. if [ -d "/etc/.git" ]; then
  1261. if [ -f "/etc/.gitignore" ]; then
  1262. if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore"; then
  1263. echo "" >> "/etc/.gitignore"
  1264. echo "x-ui/x-ui.db" >> "/etc/.gitignore"
  1265. echo -e "${green}Added x-ui.db to /etc/.gitignore for etckeeper${plain}"
  1266. fi
  1267. else
  1268. echo "x-ui/x-ui.db" > "/etc/.gitignore"
  1269. echo -e "${green}Created /etc/.gitignore and added x-ui.db for etckeeper${plain}"
  1270. fi
  1271. fi
  1272. if [[ $release == "alpine" ]]; then
  1273. curl -4fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
  1274. if [[ $? -ne 0 ]]; then
  1275. echo -e "${red}Failed to download x-ui.rc${plain}"
  1276. exit 1
  1277. fi
  1278. chmod +x /etc/init.d/x-ui
  1279. rc-update add x-ui
  1280. rc-service x-ui start
  1281. else
  1282. # Install systemd service file
  1283. service_installed=false
  1284. if [ -f "x-ui.service" ]; then
  1285. echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
  1286. cp -f x-ui.service ${xui_service}/ > /dev/null 2>&1
  1287. if [[ $? -eq 0 ]]; then
  1288. service_installed=true
  1289. fi
  1290. fi
  1291. if [ "$service_installed" = false ]; then
  1292. case "${release}" in
  1293. ubuntu | debian | armbian)
  1294. if [ -f "x-ui.service.debian" ]; then
  1295. echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
  1296. cp -f x-ui.service.debian ${xui_service}/x-ui.service > /dev/null 2>&1
  1297. if [[ $? -eq 0 ]]; then
  1298. service_installed=true
  1299. fi
  1300. fi
  1301. ;;
  1302. arch | manjaro | parch)
  1303. if [ -f "x-ui.service.arch" ]; then
  1304. echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
  1305. cp -f x-ui.service.arch ${xui_service}/x-ui.service > /dev/null 2>&1
  1306. if [[ $? -eq 0 ]]; then
  1307. service_installed=true
  1308. fi
  1309. fi
  1310. ;;
  1311. *)
  1312. if [ -f "x-ui.service.rhel" ]; then
  1313. echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
  1314. cp -f x-ui.service.rhel ${xui_service}/x-ui.service > /dev/null 2>&1
  1315. if [[ $? -eq 0 ]]; then
  1316. service_installed=true
  1317. fi
  1318. fi
  1319. ;;
  1320. esac
  1321. fi
  1322. # If service file not found in tar.gz, download from GitHub
  1323. if [ "$service_installed" = false ]; then
  1324. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  1325. case "${release}" in
  1326. ubuntu | debian | armbian)
  1327. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian > /dev/null 2>&1
  1328. ;;
  1329. arch | manjaro | parch)
  1330. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch > /dev/null 2>&1
  1331. ;;
  1332. *)
  1333. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel > /dev/null 2>&1
  1334. ;;
  1335. esac
  1336. if [[ $? -ne 0 ]]; then
  1337. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  1338. exit 1
  1339. fi
  1340. service_installed=true
  1341. fi
  1342. if [ "$service_installed" = true ]; then
  1343. echo -e "${green}Setting up systemd unit...${plain}"
  1344. chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
  1345. chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
  1346. systemctl daemon-reload
  1347. systemctl enable x-ui
  1348. systemctl start x-ui
  1349. else
  1350. echo -e "${red}Failed to install x-ui.service file${plain}"
  1351. exit 1
  1352. fi
  1353. fi
  1354. echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
  1355. echo -e ""
  1356. echo -e "┌───────────────────────────────────────────────────────┐
  1357. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  1358. │ │
  1359. │ ${blue}x-ui${plain} - Admin Management Script │
  1360. │ ${blue}x-ui start${plain} - Start │
  1361. │ ${blue}x-ui stop${plain} - Stop │
  1362. │ ${blue}x-ui restart${plain} - Restart │
  1363. │ ${blue}x-ui status${plain} - Current Status │
  1364. │ ${blue}x-ui settings${plain} - Current Settings │
  1365. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  1366. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  1367. │ ${blue}x-ui log${plain} - Check logs │
  1368. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  1369. │ ${blue}x-ui update${plain} - Update │
  1370. │ ${blue}x-ui legacy${plain} - Legacy version │
  1371. │ ${blue}x-ui install${plain} - Install │
  1372. │ ${blue}x-ui uninstall${plain} - Uninstall │
  1373. └───────────────────────────────────────────────────────┘"
  1374. }
  1375. echo -e "${green}Running...${plain}"
  1376. install_base
  1377. install_x-ui $1