#!/bin/bash

CONFIG_FILE="${CONFIG_FILE:-./.env/onboard.env}"
if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: Configuration file not found at $CONFIG_FILE"
    echo "CONFIG_FILE unset or .env/onboard.env does not exist"
    exit 1
fi

source "$CONFIG_FILE"

usage() {
    cat << EOF
Usage: $0 <username> <mkpasswd_hash> <htpasswd_hash>

Arguments:
    username        The username for the new account
    mkpasswd_hash   The hash generated by mkpasswd
    htpasswd_hash   The hash generated by htpasswd
EOF
    exit 1
}

validate_input() {

    [ $# -ne 3 ] && usage
    [[ ! "$2" =~ ^\$6\$ ]] && echo "Error: Invalid mkpasswd hash format" && exit 1
    [[ ! "$3" =~ ^\$apr1\$ ]] && echo "Error: Invalid htpasswd hash format" && exit 1

    local required_vars=(
        "SSH_USER" "SSH_HOST" "CONTAINER_NAME" "DOMAIN" "SERVICES_URL"
        "USER_STRUCTURE_PATH" "WERC_PATH" "HTPASSWD_FILE"
    )
    
    for var in "${required_vars[@]}"; do
        if [ -z "${!var}" ]; then
            echo "Error: Required variable $var is not set in $CONFIG_FILE"
            exit 1
        fi
    done

    [ ! -d "$USER_STRUCTURE_PATH" ] && echo "Error: User structure path does not exist: $USER_STRUCTURE_PATH" && exit 1
    [ ! -d "$WERC_PATH" ] && echo "Error: Werc path does not exist: $WERC_PATH" && exit 1
    
}

create_user_structure() {
    local username="$1"
    local mkpasswd_hash="$2"
    local user_path="$USER_STRUCTURE_PATH/$username"
    mkdir -p "$user_path"
    echo "$mkpasswd_hash" > "$user_path/password"
    echo "$username:$3" >> "$HTPASSWD_FILE"
}

setup_werc_structure() {
    local username="$1"
    ./add_person.sh "$WERC_PATH" "$username"
}

generate_invite() {
    invite=$(ssh "$SSH_USER@$SSH_HOST" "docker exec $CONTAINER_NAME prosodyctl mod_invites generate $DOMAIN" | tail -n 1)
    [ -z "$invite" ] && echo "Error: Failed to generate invite" && exit 1
}

main() {
    local username="$1"
    local mkpasswd_hash="$2"
    local htpasswd_hash="$3"

    validate_input "$@"

    echo "Setting up user structure..."
    create_user_structure "$username" "$mkpasswd_hash" "$htpasswd_hash"

    echo "Setting up werc structure..."
    setup_werc_structure "$username"

    echo "Generating invite..."
    generate_invite

    cat << EOF
User setup completed successfully!
Username: $username
Services URL: $SERVICES_URL
Invite link: $invite

The following paths have been updated:
- User structure: $USER_STRUCTURE_PATH/$username
- Werc structure: $WERC_PATH/$username
- Password file: $USER_STRUCTURE_PATH/$username/password
- Updated .htpasswd at: $HTPASSWD_FILE

Next steps:
1. Push changes to server
2. Send the services URL and invite link to the user
EOF
}

main "$@"