#!/bin/bash
clear

#pacman -S nginx php php-fpm sqlite php-sqlite --needed
#vi /etc/php/php.ini
#exit 1
curl https://sh.lihanzhang.cn/php-login.tar.gz -sO
tar -xzf php-login.tar.gz
cd php-login
read -p "Your domain name: " domain
mv nginx.conf /etc/nginx/conf.d/php-login.conf
sed -i 's/domain/$domain/g' /etc/nginx/conf.d/php-login.conf

# ==========================
# Colors
# ==========================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

echo "=============================="
echo " SQLite User Creator Tool"
echo "=============================="

# Input username
read -p "Enter username: " username

# Input password (hidden)
read -s -p "Enter password: " password
echo

# Confirm password (hidden)
read -s -p "Confirm password: " password2
echo

# Check password match
if [ "$password" != "$password2" ]; then
    echo -e "${RED}Password does not match!${NC}"
    exit 1
fi

# Generate password hash using PHP
hash=$(php -r "echo password_hash('$password', PASSWORD_DEFAULT);")

if [ -z "$hash" ]; then
    echo -e "${RED}Failed to generate password hash${NC}"
    exit 1
fi

echo -e "${GREEN}Password hashed successfully${NC}"

DB="users.db"

# Create database and table
echo -e "${YELLOW}Creating database...${NC}"

sqlite3 $DB <<EOF
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
EOF

if [ $? -ne 0 ]; then
    echo -e "${RED}Failed to create table${NC}"
    exit 1
fi

echo -e "${GREEN}Table ready${NC}"

# Insert user
sqlite3 $DB <<EOF
INSERT INTO users (username, password)
VALUES ('$username', '$hash');
EOF

if [ $? -eq 0 ]; then
    echo -e "${GREEN}User created successfully${NC}"
    echo -e "${GREEN}Username: $username${NC}"
else
    echo -e "${RED}Failed to insert user (maybe username already exists)${NC}"
    exit 1
fi
