#!/bin/bash

set -e

SHADOWSOCKS_DIR="/usr/local/shadowsocks/"
SERVICE_FILE="/etc/systemd/system/shadowsocks.service"

rm -rf "$SHADOWSOCKS_DIR"
mkdir -p "$SHADOWSOCKS_DIR"

cd "$SHADOWSOCKS_DIR"

if ! wget https://soft.lnmp.top/linux/ss/v1.24.0.x86_64.tar; then
    echo "Failed to download Shadowsocks server."
    exit 1
fi

if ! tar -xf v1.24.0.x86_64.tar ssserver; then
    echo "Failed to extract Shadowsocks server."
    exit 1
fi

PASSWORD=$(openssl rand -base64 12)

cat <<EOF >"${SHADOWSOCKS_DIR}config.json"
{
    "server": "0.0.0.0",
    "server_port": 800,
    "password": "$PASSWORD",
    "timeout": 600,
    "method": "aes-256-gcm"
}
EOF

cat <<EOF >"$SERVICE_FILE"
[Unit]
Description=Shadowsocks Server
After=network.target

[Service]
ExecStart=${SHADOWSOCKS_DIR}ssserver -c ${SHADOWSOCKS_DIR}config.json
Restart=on-abort

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start shadowsocks
systemctl enable shadowsocks

if systemctl is-active --quiet shadowsocks; then
    echo "Shadowsocks server started successfully."
    echo "Encryption method: aes-256-gcm"
    echo "Password: $PASSWORD"
else
    echo "Failed to start Shadowsocks server."
    exit 1
fi