#!/bin/bash
# C64U FTP server setup for Raspberry Pi OS
# Installs vsftpd, creates the c64 FTP account, writes the settings, and creates all folders.
set -e

echo "=== C64U FTP server setup ==="
read -s -p "Choose a password for the c64 FTP account: " P1; echo
read -s -p "Type it again: " P2; echo
if [ "$P1" != "$P2" ] || [ -z "$P1" ]; then
  echo "Passwords don't match (or are empty). Run the script again."
  exit 1
fi

echo "--- Installing the FTP server (vsftpd) ---"
sudo apt update
sudo apt install -y vsftpd

echo "--- Creating the c64 account ---"
id c64 >/dev/null 2>&1 || sudo adduser --disabled-password --gecos "" c64
echo "c64:$P1" | sudo chpasswd
echo c64 | sudo tee /etc/vsftpd.userlist >/dev/null

echo "--- Writing the FTP settings ---"
[ -f /etc/vsftpd.conf.original ] || sudo cp /etc/vsftpd.conf /etc/vsftpd.conf.original
sudo tee /etc/vsftpd.conf >/dev/null <<'CONF'
listen=YES
listen_ipv6=NO
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
chroot_local_user=YES
allow_writeable_chroot=YES
pasv_enable=YES
pasv_min_port=40000
pasv_max_port=40100
userlist_enable=YES
userlist_file=/etc/vsftpd.userlist
userlist_deny=NO
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
xferlog_enable=YES
CONF

echo "--- Creating folders ---"
H=/home/c64
# Suggested layout
sudo -u c64 mkdir -p "$H"/games/{0-9,{A..Z}} "$H"/multidisk "$H"/carts "$H"/tapes \
  "$H"/demos "$H"/music "$H"/utilities "$H"/config "$H"/upload
# Your collection's folders
for d in "000 Configs" 000_TeensyRom 000-ORISD 000-ORIusb 000-Unsorted \
  00-BBS 00-Compute 00-DEMOS 00-EXCLUSIVE 00-GAMES 00-MUSIC 00-PUBLISHERS \
  001-Maverick "blank disks" Christmas Commander64 Copy CSDB favorites \
  firmwares "GameBase SD_Main" "GEOS Swap Disks" Magazine Outrage \
  printfiles PrintMaster Sonic Utilities; do
  sudo -u c64 mkdir -p "$H/$d"
done

echo "--- Starting the FTP server ---"
sudo systemctl restart vsftpd
sudo systemctl enable vsftpd >/dev/null 2>&1

IP=$(hostname -I | awk '{print $1}')
echo
echo "=== Done! ==="
echo "Folders created: $(sudo ls /home/c64 | wc -l)"
echo
echo "On the C64U: File Browser > ftp > RETURN > New Host"
echo "  Alias:    Pi"
echo "  Host:     $IP"
echo "  Port:     21"
echo "  User:     c64"
echo "  Password: (the one you just chose)"
echo "  Path:     /"
